Home > other >  how to pass data between two pages in flutter using bottom navigation bar
how to pass data between two pages in flutter using bottom navigation bar

Time:09-17

i'm new in flutter world. i'm using bottom navigation bar but i don't have idea how to pass data from bottom navigation bar page to homepage since homepage is expecting 1 parameter. i'm passing data between other pages but i couldn't find a way to pass data between bottomnavigation bar and home page. any help would be apprecaited thanks in advance

this is my navigation page code

import 'package:chat_app/models/user_model.dart';
import 'package:chat_app/screens/call_log_screen.dart';
import 'package:chat_app/screens/chat_screen.dart';
import 'package:chat_app/screens/home_screen.dart';
import 'package:chat_app/screens/search_screen.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class CustomBottomNavigationBar extends StatefulWidget {
  UserModel user;
  CustomBottomNavigationBar(this.user);
  @override
  _CustomBottomNavigationBarState createState() =>
      _CustomBottomNavigationBarState();
}

class _CustomBottomNavigationBarState extends State<CustomBottomNavigationBar> {
  int _selectedIndex = 0;
  late final screens = [
    HomeScreen(widget.user),
    CallLog(),
    CallLog(),
    CallLog(),
  ];

  void onTapped(int index) {
    print(widget.user.name);
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: screens[_selectedIndex],
      bottomNavigationBar: BottomNavigationBar(
        backgroundColor: Colors.black,
        selectedIconTheme: IconThemeData(color: Colors.blue),
        currentIndex: 2,
        items: [
          BottomNavigationBarItem(
            icon: Icon(
              CupertinoIcons.settings,
              color: Colors.grey,
            ),
            label: 'hi',
          ),
          BottomNavigationBarItem(
            icon: Icon(
              CupertinoIcons.home,
              color: Colors.grey,
            ),
            label: 'hi',
          ),
          BottomNavigationBarItem(
            icon: Icon(
              CupertinoIcons.phone,
              color: Colors.grey,
            ),
            label: 'hi',
          ),
          BottomNavigationBarItem(
            icon: Icon(
              CupertinoIcons.chat_bubble_text,
              color: Colors.grey,
            ),
            label: 'hi',
          ),
        ],
        onTap: onTapped,
      ),
    );
  }
}

and this is my homepage code

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat_app/models/user_model.dart';
import 'package:chat_app/screens/chat_screen.dart';
import 'package:chat_app/screens/search_screen.dart';
import 'package:chat_app/widgets/bottom_navigation_bar.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:intl/intl.dart';

import 'auth_screen.dart';

class HomeScreen extends StatefulWidget {
  UserModel user;
  HomeScreen(this.user);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance!.addObserver(this);
    setStatus('online');
  }

  void setStatus(String status) async {
    await FirebaseFirestore.instance
        .collection('users')
        .doc(widget.user.uid)
        .update({"userStatus": status});
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    if (state == AppLifecycleState.resumed) {
      //online
      setStatus("online");
    } else {
      //offline
      setStatus('offline');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
        centerTitle: true,
        backgroundColor: Colors.deepPurple,
        actions: [
          IconButton(
            onPressed: () async {
              await GoogleSignIn().signOut();
              await FirebaseAuth.instance.signOut();
              setStatus('offline');
              Navigator.pushAndRemoveUntil(
                  context,
                  MaterialPageRoute(
                    builder: (context) => AuthScreen(),
                  ),
                  (route) => false);
            },
            icon: Icon(Icons.logout),
          ),
        ],
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection('users')
            .doc(widget.user.uid)
            .collection('messages')
            .snapshots(),
        builder: (context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data.docs.length < 1) {
              return Center(
                child: Text('No Chat Available!!!'),
              );
            }
            return ListView.builder(
              itemCount: snapshot.data.docs.length,
              itemBuilder: (context, index) {
                var friendId = snapshot.data.docs[index].id;
                var lastMsg = snapshot.data.docs[index]['last_message'];
                var lastMsgTime =
                    snapshot.data.docs[index]['last_message_time'];

                return FutureBuilder(
                  future: FirebaseFirestore.instance
                      .collection('users')
                      .doc(friendId)
                      .get(),
                  builder: (context, AsyncSnapshot asyncSnapShot) {
                    if (asyncSnapShot.hasData) {
                      var friend = asyncSnapShot.data;
                      return ListTile(
                        leading: ClipRRect(
                          borderRadius: BorderRadius.circular(80.0),
                          child: CachedNetworkImage(
                            imageUrl: friend['image'],
                            placeholder: (context, url) =>
                                CircularProgressIndicator(),
                            errorWidget: (context, url, error) =>
                                Icon(Icons.error),
                          ),
                          // child: Image.network(
                          //   friend['image'],
                          // ),
                        ),
                        trailing: Text(
                          DateFormat.jm().format(
                            lastMsgTime.toDate(),
                          ),
                        ),
                        title: Text(
                          friend['name'],
                        ),
                        subtitle: Text(
                          "$lastMsg",
                          style: TextStyle(color: Colors.grey),
                          overflow: TextOverflow.ellipsis,
                        ),
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => ChatScreen(
                                currentUser: widget.user,
                                receiverId: friend['uid'],
                                receiverImage: friend['image'],
                                receiverName: friend['name'],
                              ),
                            ),
                          );
                        },
                      );
                    }

                    return LinearProgressIndicator();
                  },
                );
              },
            );
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => SearchScreen(widget.user),
            ),
          );
          // Navigator.pushAndRemoveUntil(
          //     context,
          //     MaterialPageRoute(
          //       builder: (context) => SearchScreen(widget.user),
          //     ),
          //     (route) => false);
        },
        child: Icon(CupertinoIcons.search),
      ),
      bottomNavigationBar: CustomBottomNavigationBar(widget.user),
    );
  }
}

CodePudding user response:

You can't access instance member widget in an initializer.

Try this

class _CustomBottomNavigationBarState extends State<CustomBottomNavigationBar> {
  int _selectedIndex = 0;
  late final List screens;

  @override
  void initState() {
    super.initState();

    screens = [
      HomeScreen(widget.user),
      CallLog(),
      CallLog(),
      CallLog(),
    ];
  }
...
// the rest of your code

CodePudding user response:

Try using this package Bottom Navigation Bar

  • Related