Nibbles
Nibbles

Reputation: 55

How do I integrate Universal Links mockup with an existing app?

I have 2 test apps that I need help to integrate. One app is a successful mockup for universal links (it offers to redirect to one of 2 pages depending on the website url a user visits), and the other app has my content successfully displaying (a home page of factfiles updates (ItemList), and a page to show a given factfile (ItemDetails)).

Please could someone point me in the right direction for how to integrate the two apps? e.g. the first app uses GoRoute but the second app uses "routes", so I'm not sure how to slot the 2nd app's code into the first?

1st app: import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart';

void main() => runApp(MaterialApp.router(routerConfig: router));

final router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (_, __) => Scaffold(
        appBar: AppBar(title: const Text('Home')),
      ),
      routes: [
        GoRoute(
          path: 'factfiles/FactfileName',
          builder: (_, __) => Scaffold(
            appBar: AppBar(title: const Text('Factfile')),
          ),
        ),
      ],
    ),
  ],
);

2nd app:

import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:url_launcher/url_launcher.dart';
import 'firebase_options.dart';


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  runApp(Home());
}

class Home extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,

      title: 'TITLE',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),

      routes: {
        '/': (context) => ItemList(),
        '/factfile': (context) => ItemDetails(),
      },
    );
  }
}

class ItemList extends StatefulWidget {
  _ItemListState createState() => _ItemListState();
}

class _ItemListState extends State {

    _ItemListState({Key? key}) {
    _stream = _reference.snapshots();
    _foundItems = items; // Initialize _foundItems with items
  }

  final Query _reference = FirebaseFirestore.instance.collection('home_COLLECTION').orderBy(
      "dlastupd", descending: true);
  late final Stream<QuerySnapshot> _stream;
  late List<Map<dynamic, dynamic>> _foundItems;
  final List<Map<dynamic, dynamic>> items = [];

  void _runFilter(String enteredKeyword) {
    setState(() {

      if (enteredKeyword.isEmpty) {
        _foundItems = items;
      } else {
        _foundItems = items
            .where((item) =>
            item["name"].toLowerCase().contains(enteredKeyword.toLowerCase()))
            .toList();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Updates'),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(18.0),
            child: TextField(
              onChanged: (value) => _runFilter(value),
              decoration: InputDecoration(
                  labelText: 'Search', suffixIcon: Icon(Icons.search)),
            ),
          ),
          const SizedBox(
            height: 20,
          ),
          Expanded(
            child: StreamBuilder<QuerySnapshot>(
              stream: _stream,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.hasError) {
                  return Center(child: Text('Some error occurred ${snapshot.error}'));
                }
                if (snapshot.hasData) {
                  QuerySnapshot querySnapshot = snapshot.data;
                  List<QueryDocumentSnapshot> documents = querySnapshot.docs;
                  items.clear(); // Clear items to avoid duplication
                  items.addAll(documents.map((e) =>
                  {
                    'name': e['name'],
                    'country': e['country'],
                    'dlastupd': e['dlastupd'],
                    'dlastupd date': DateTime.fromMillisecondsSinceEpoch(
                        e['dlastupd'] * 1000),
                    'id': e['id'],
                    'overallrecsit': e['overallrecsit'],
                    'type': e['type'],
                  }));

                  return ListView.builder(

                      itemCount: _foundItems.length,
                      itemBuilder: (BuildContext context, int index) {
                        Map thisItem = _foundItems[index];

                        var overallrecsitAbridged = thisItem['overallrecsit'] == "Positive" ? "+VE"
                            : thisItem['overallrecsit'] == "Neutral" ? "N"
                            : thisItem['overallrecsit'] == "Negative" ? "-VE" : "?";

                        Color overallrecsitAbridgedColor = thisItem['overallrecsit'] == "Positive" ? Colors.green
                            : thisItem['overallrecsit'] == "Neutral" ? Colors.amber
                            : thisItem['overallrecsit'] == "Negative" ? Colors.red : Colors.black;

                        //Return the widget for the list items
                        return ListTile(
                          title:

                          Text.rich(
                              TextSpan(
                                  children: [
                                    TextSpan(text: formatDate(thisItem['dlastupd date'], [d, '', M]) + " " + thisItem['country'] + " (" + thisItem['type'][0] + thisItem['type'][1] + ") - " + thisItem['name'] + " " ,
                                        style: TextStyle(fontWeight: FontWeight.normal)),
                                    TextSpan(text: overallrecsitAbridged,
                                        style: TextStyle(fontWeight: FontWeight.bold, color: overallrecsitAbridgedColor

                                        )),
                                  ]
                              )
                          ),

                          onTap: () {
                            Navigator.pushNamed(
                              context,
                              '/factfile',
                              arguments: {
                                'id': thisItem['id'],
                              },
                            );
                          },
                        );
                      });
                }
                return Center(child: CircularProgressIndicator());
              },
            ),
          ),
        ],
      ),
    );
  }
}

class ItemDetails extends StatelessWidget {

  Map routeData = {};

  @override
  Widget build(BuildContext context) {
    routeData = ModalRoute
        .of(context)
        ?.settings
        .arguments as Map;

    final Query docRef = FirebaseFirestore.instance.collection("COLLECTION_NAME").where(
        "id", isEqualTo: routeData['id']);

    return FutureBuilder<QuerySnapshot>(
        future: docRef. get (),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {

            return Scaffold(
              appBar: AppBar(
                title: Text("Loading..."),
              ),
              body: Center(child: CircularProgressIndicator()),
            );
          } else if (snapshot.hasError) {
            return Scaffold(
              appBar: AppBar(
                title: Text("Error"),
              ),
              body: Center(child: Text("Error: ${snapshot.error}")),
            );
          } else {

            var querySnapshot = snapshot.data!;
            var docs = querySnapshot.docs;
            final data = docs[0].data() as Map<String, dynamic>;

            final yourScrollController = ScrollController();
            return Scaffold(

                appBar: AppBar(
                  title: Text(data?["name"]),
                ),



                body: SingleChildScrollView(
                    child: Container(
                        margin: const EdgeInsets.all(10.0),

                        child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text.rich(
                                  TextSpan(
                                      children: [
                                        TextSpan(text: "Country: ",
                                            style: TextStyle(fontWeight: FontWeight.bold)),
                                        TextSpan(text: data?["country"] + "\n"),
                                        TextSpan(text: "Region: ",
                                            style: TextStyle(fontWeight: FontWeight.bold)),
                                        TextSpan(text: data?["reg"] + "\n"),
                                        TextSpan(text: "Type: ",
                                            style: TextStyle(fontWeight: FontWeight.bold)),
                                        TextSpan(text: data?["type"] + "\n"),
                                        TextSpan(text: "Red text last updated: ",
                                            style: TextStyle(fontWeight: FontWeight.bold)),

                                        TextSpan(text: formatDate(
                                            DateTime.fromMillisecondsSinceEpoch(
                                                data?['dlastupd'] * 1000),
                                            [d, ' ', MM, ' ', yyyy]) + "\n"),
                                      ] // children
                                  )
                              ),
                              // text
                            ]
                        )
                    )
                )
            );
          }
          },
    );
  }
}

Future<void> goToWebPage(String urlString) async {
  final Uri _url = Uri.parse(urlString);
  if (!await launchUrl(_url)) {
    throw 'Could not launch $_url';
  }
}

Many thanks for your help,

N

Upvotes: 0

Views: 19

Answers (0)

Related Questions