Ad

Flutter Error Type 'Null' Is Not A Subtype Of Type 'String'

- 1 answer

so i want to print user name and user username in the profile page and in the end it shows it but for a few seconds there is a red screen that says The following _TypeError was thrown building Profile_page(dirty, state: _Profile_pageState#68414): type 'Null' is not a subtype of type 'String'

this is the code of main.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/name.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question1.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question2.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question3.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question4.dart';
import 'package:gp1_7_2022/screen/auth/signup/Questions/question5.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/photo.dart';
import 'package:gp1_7_2022/screen/home/Profile_Page.dart';
import 'package:firebase_core/firebase_core.dart';
/*pages */
import 'package:gp1_7_2022/screen/auth/signup_login.dart';
import 'package:gp1_7_2022/screen/auth/signup/userAuth/signup.dart';
import 'package:gp1_7_2022/screen/auth/Login/login.dart';
import 'package:gp1_7_2022/screen/auth/signup/userAuth/signupConfirmationCode.dart';
import 'package:gp1_7_2022/screen/auth/signup/userAuth/signupPassword.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/signupBirthday.dart';
import 'package:gp1_7_2022/screen/auth/signup/userInfo/signupUsername.dart';
import 'package:gp1_7_2022/screen/auth/Login/forget_password.dart';
import 'package:gp1_7_2022/screen/settings.dart';
void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(
      MaterialApp(
          initialRoute: "/",
          routes: {
            "/": (context) => MainPage(),
            "/signup": (context)=> Signup(),
            '/login':(context)=>Login(),
            '/Profile_Page':(context) => Profile_page(uid: FirebaseAuth.instance.currentUser!.uid),
            // '/confirmationCode':(context) => ConfirmationCode(),
            // '/signupPassword':(context) => signupPassword(),
            '/signupBirthday':(context) => SignupBirthday(),
            '/signupUsername':(context) => SignupUsername(),
           '/forget_password':(context) => forget_password(),
            '/name':(context) => name(),
            '/question1':(context) => question1(),
            '/question2':(context) => question2(),
            '/question3':(context) => question3(),
            '/question4':(context) => question4(),
            '/question5':(context) => question5(),
            '/photo':(context) => Photo(),
            '/settings':(context) => settings(),
          }
      )
  );
}
class MainPage extends StatelessWidget {
  const MainPage({Key? key}) : super(key: key);



  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: StreamBuilder<User?>(

        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, snapshot){
          if(snapshot.connectionState==ConnectionState.waiting){
            return const Center(child: CircularProgressIndicator());
          }else if(snapshot.hasError){
            return const Center(child: Text("Something went wrong!"));
          }else if(snapshot.hasData){
            if(FirebaseAuth.instance.currentUser!.emailVerified && FirebaseAuth.instance.currentUser!.uid != null ){
              String uid = FirebaseAuth.instance.currentUser!.uid;
              return  Profile_page(uid: uid );
            }else{
              String? x = FirebaseAuth.instance.currentUser!.email;
              String y= x??" ";
              return  ConfirmationCode(email: y);
            }
          } else{
            return const Signup_Login();

          }
        },
      ),
    );
  }
}

this is the code of profile_page.dart

// import 'dart:html';

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:focused_menu/focused_menu.dart';
import 'package:focused_menu/modals.dart';
/*pages */
/*colors */
import 'package:gp1_7_2022/config/palette.dart';
import 'package:gp1_7_2022/Widgets/follow_button.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:gp1_7_2022/screen/settings.dart';

class Profile_page extends StatefulWidget {
  final uid;
  const Profile_page({Key? key, required this.uid}) : super(key: key);

  @override
  State<Profile_page> createState() => _Profile_pageState();
}

class _Profile_pageState extends State<Profile_page> {
  var padding= 0.8;
  var userData = {};
  @override
  void initState() {
    super.initState();
    getData();
  }
  /* get data method */
  getData() async {
  try {
    if (widget.uid != null) {
      var userSnap = await FirebaseFirestore.instance.collection('users').doc(
          widget.uid).get();
      userData = userSnap.data()!;
      setState(() {

      });
    }
  }
    catch(e){
      Alert(
          context: context,
          title: "Something went wrong!",
          desc: e.toString(),
      ).show();
    }

  }
  
  
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Palette.backgroundColor,

      appBar: AppBar(
        //appBar style
        elevation: 0,
        backgroundColor: Palette.backgroundColor,
        automaticallyImplyLeading: false,//no arrow
        //username
        title:  Padding(
          padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
          child: Text(
              userData['username'],
            style: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.bold,
              fontSize: 24,
            ),
          ),
        ),

        //setting icon
        actions:[
          FocusedMenuHolder(
            //
            menuWidth: MediaQuery.of(context).size.width * 0.4,
            menuOffset: 0,
            menuItemExtent: 49,

            //list
            menuItems: [
              FocusedMenuItem(
                  title: const Text("Log out"),
                  trailingIcon: const Icon(Icons.logout),
                  onPressed: (){
                    /*go to sign up page*/
                    Navigator.pushNamed(context, '/');
                    return FirebaseAuth.instance.signOut();
                  }
              ),
              FocusedMenuItem(
                  title: const Text("Settings"),
                  trailingIcon: const Icon(Icons.settings),
                  onPressed: (){
                    Navigator.of(context).popAndPushNamed('/settings');


                  },
              ),
            ],

            openWithTap: true,
            onPressed: (){},

            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24),
              child: Image.asset(
                "assets/menu-icon.png",
                height: 25,
                width: 25,
              ),
            ),

          ),
        ],
      ),

      body: ListView(
        children: [
          Container(
            margin: const EdgeInsets.all(16),
            child: Column(
              children: [
                Row(
                  children: [
                    //user photo
                    const Padding(
                      padding: EdgeInsets.fromLTRB(0, 0, 40, 0),
                      child: CircleAvatar(
                      backgroundColor: Colors.white ,

                        child:  Icon(
                       Icons.account_circle_sharp,
                       color: Colors.grey,
                       size: 90,


                    ),


                      ),
                    ),
                    //end user photo

                    Expanded(
                      flex: 7,
                      child: Column(
                        children: [
                          SizedBox(height:40,),
                          //post, followers and following
                          Row(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              buildStatColumn(20, "posts"),
                              buildStatColumn(150, "Followers"),
                              buildStatColumn(10, "Following"),
                            ],
                          ),
                          //end post, followers and following

                        ],
                      ),
                    ),
                  ],
                ),

                //username
                Container(
                  alignment: Alignment.centerLeft,
                  padding:  EdgeInsets.fromLTRB(10, 40, 0, 0),
                  child:  Text(
                    userData['name'],
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                ),
                //end of username

                //bio
                Container(
                  alignment: Alignment.centerLeft,
                  padding: const EdgeInsets.fromLTRB(10, 1, 0, 0),
                  child: const Text(
                    'bio',
                    style: TextStyle(
                      fontSize: 16,
                    ),
                  ),
                ),
                //end of bio

                //edit profile button
                Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    FollowButton(
                      text: 'Edit profile',
                      backgroundColor: Palette.backgroundColor,
                      borderColor: Palette.grey,
                      textColor: Colors.black,
                      function: () {},
                    )
                  ],
                ),
                //end of button



              ],
            ),
          ),
        ],
      ),
    );
  }
}





// function to show following/followers/# of posts

Column buildStatColumn(int num, String label) {
  return Column(
    mainAxisSize: MainAxisSize.min,
    mainAxisAlignment: MainAxisAlignment.center,
    children: [

      Text(
        num.toString(),
        style: const TextStyle(
          fontSize: 20,
          fontWeight: FontWeight.bold,

        ),

      ),


      Container(
        margin: const EdgeInsets.only(top: 4),
        child: Text(
          label,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w400,
            color: Colors.grey,
          ),

        ),
      ),

    ],

  );

}

enter image description here

Ad

Answer

Show some other widgets until data is not fully loaded.

class _Profile_pageState extends State<Profile_page> {
  ...
  bool _isloaded = false;      // Add this boolean

In getData function

    getData() async {
  try {
    ...
      setState(() {
      _isloaded = true;      // when data is loaded update state
      });
    }
  ...

In build, return widget according to data(user)

@override
Widget build(BuildContext context) {
    return _isloaded == false ?
    Center(
       child: CircularProgressIndicator(), // Show indicator 
    )
    : Scaffold(   
       backgroundColor: Palette.backgroundColor,
    ...
    ); //Scaffold
Ad
source: stackoverflow.com
Ad