Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

api - the method was called on null in flutter

greeting to all, I am stuck in a situation where I am getting data from the back end but initially it the error is displayed on the phone before the app starts. below is the image of the error.

enter image description here

after showing this the app starts. how do I handle this error? I tried the spin kit but it is not working. I want to show this on the console. below is the code -:

import 'package:education/LogIn_SignUp/Log_In.dart';
import 'package:education/Screens/Profile_Screen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'About_Scree.dart';
import 'Change_Password.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';



class homeView extends StatefulWidget{

  var user_id;
  var user_name;
  var mobile_number;
  var user_address;
  var user_Email;
  var coaching_id;
  var coaching_name;
  var coaching_address;
  var primary_no;
  var altnumber;
  var coaching_email;



  homeView({
    this.user_id,this.user_name,this.mobile_number,this.user_address,this.coaching_id,this.coaching_name,
    this.coaching_address,this.primary_no,this.altnumber,this.coaching_email,this.user_Email
});

  @override
  State<StatefulWidget> createState() => homeViewState();
}



class homeViewState extends State<homeView> {


  TextEditingController editingController = TextEditingController();

  var showItemList = List<String>();
  int count = 10;




  var userid, username, mobilenumber, useraddress, userEmail, coachingid, coachingname, coachingaddress;
  var primaryno, alt_number, coachingemail;

  void setdata(){
    setState(() {
      userid = widget.user_id;
      username = widget.user_name;
      mobilenumber = widget.mobile_number;
      useraddress = widget.user_address;
      userEmail = widget.user_Email;
      coachingid = widget.coaching_id;
      coachingname = widget.coaching_name;
      coachingaddress = widget.coaching_address;
    });
  }



  @override
  void initState(){
    // showItemList.addAll(initList);
    // getData();
    setdata();
    super.initState();
  }


  @override
  void dispose() {
    editingController.dispose();
    super.dispose();
  }

  /// -----------------------------------------------------------------------------------------------------------------------------
  ///                                           Main Build Function for the class.
  /// -----------------------------------------------------------------------------------------------------------------------------


  @override
  Widget build(BuildContext context) {

    return SafeArea(
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(90.0),
          child: AppBar(
            title: Padding(
              padding: const EdgeInsets.only(top: 20),
              child: Text(
                '$coachingname',//'${widget.coaching_name}',
                style: TextStyle(
                  fontSize: 25.0,
                  letterSpacing: 4.5,
                  fontFamily: 'Sarif',
                  fontWeight: FontWeight.w300,
                  color: Colors.white,
                ),
              ),
            ),
            backgroundColor: Colors.deepPurpleAccent,
            centerTitle: true,
            actions: <Widget>[
              Column(
                children: [
                  InkWell(
                    child: new IconButton(
                        icon: Padding(
                          padding: const EdgeInsets.only(top: 20),
                          child: Icon(Icons.exit_to_app),
                        ),
                        onPressed:(){
                          Navigator.pushReplacement(context, MaterialPageRoute(
                            builder: (context) => LoginPage(),
                          ));
                        }
                    ),
                    onTap: (){
                      Navigator.pushReplacement(context, MaterialPageRoute(
                        builder: (context) => LoginPage()
                      ));
                    },
                  ),
                ],
              ),
            ],
          ),
        ),
        drawer: Drawer(
          child: Container(
            padding: EdgeInsets.all(10),
            child: ListView(
              children: <Widget>[

                Container(
                  height: 180,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(colors: [
                      Colors.purple.shade300,
                      Colors.deepPurpleAccent.shade200,
                    ]),
                  ),
                  child: Column(
                    children: [

                      Padding(
                        padding: const EdgeInsets.only(top: 45.0, bottom: 10),
                        child: Card(
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(55),
                            ),
                            color: Colors.blue,
                            child: Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: Icon(Icons.perm_identity_outlined, color: Colors.white,size: 30),
                            )
                        ),
                      ),

                      Text(
                        '$username',//'${widget.user_name}',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 24,
                          letterSpacing: 2.5,
                        ),
                      ),


                    ],
                  ),
                ),


                ListTile(
                  title: Text('Profile',
                    style: TextStyle(
                    fontSize: 17,
                    fontWeight: FontWeight.w400,
                    letterSpacing: 1.5,
                  ),
                  ),
                  leading: Icon(Icons.person_pin, color: Colors.blue,),
                  selectedTileColor: Colors.blue,
                  onTap: (){
                    Navigator.pushReplacement(context, MaterialPageRoute(
                      builder: (context) => ProfilePage(
                        user_id: userid, user_name:username, mobile_number:mobilenumber, user_address:useraddress,
                        user_Email: userEmail,
                      )
                    ));
                  },
                ),

                ListTile(
                  title: Text('Change Password',
                    style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w400,
                      letterSpacing: 1.5,
                    ),
                  ),
                  leading: Icon(Icons.security, color: Colors.blue,),
                  selectedTileColor: Colors.blue,
                  onTap: (){
                    Navigator.pushReplacement(context, MaterialPageRoute(
                      builder: (context) => ChangePassword()
                    ));
                  },
                ),

                ListTile(
                  title: Text('About',
                    style: TextStyle(
                    fontSize: 17,
                    fontWeight: FontWeight.w400,
                    letterSpacing: 1.5,
                  ),
                ),
                  leading: Icon(Icons.info_outline, color: Colors.blue,),
                  selectedTileColor: Colors.blue,
                  onTap: (){
                    Navigator.pushReplacement(context, MaterialPageRoute(
                      builder: (context) => AboutScreen(
                        coaching_id:coachingid, coaching_name:coachingname, coaching_address:coachingaddress,
                        primary_no:primaryno, altnumber:alt_number, coaching_email:coachingemail
                      )//coaching details
                    ));
                  },
                ),

                ListTile(
                  title: Text(
                    'Rate',
                    style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w400,
                      letterSpacing: 1.5,
                    ),
                  ),
                  leading: Icon(Icons.star_border_outlined, color: Colors.blue,),
                  selectedTileColor: Colors.blue,
                  onTap: (){

                  },
                ),


                Divider(
                  color: Colors.red,
                  thickness: 1,
                ),


                SizedBox(height: 10,),

                Text(
                  'Contact Us',
                  style: TextStyle(
                    fontSize: 20,
                    color: Colors.grey[800],
                    letterSpacing: 1.5,
                    fontWeight: FontWeight.w500,
                  ),
                ),

                SizedBox(height: 10,),

                ListTile(
                  title: Text('Share',
                    style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w400,
                      letterSpacing: 1.5,
                    ),
                  ),
                  leading: Icon(Icons.share, color: Colors.blue,),
                  selectedTileColor: Colors.blue,
                  onTap: (){

                  },
                ),

                ListTile(
                  title: Text('Privacy Policy',
                    style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w400,
                      letterSpacing: 1.5,
                    ),
                  ),
                  leading: Icon(Icons.privacy_tip, color: Colors.blue,),
                  selectedTileColor: Colors.blue,
                  onTap: (){

                  },
                ),

                ListTile(
                  title: Text(
                    'LogOut',
                    style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w400,
                      letterSpacing: 1.5,
                    ),
                  ),
                  leading: Icon(Icons.logout, color: Colors.blue,),
                  selectedTileColor: Colors.blue,
                  onTap: (){
                    Navigator.pushReplacement(context, MaterialPageRoute(
                      builder: (context) => LoginPage()
                    ));

                  },
                ),



              ],
            ),
          ),
        ),
        body: Container(),
      ),
    );
  }
}

can I have some idea to handle this thing?

this is the exception shown on console -:

 ════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building LoginPage(dirty, dependencies: [MediaQuery], state: LoginPageState#6cbef(ticker active)):
LoginPageState is a SingleTickerProviderStateMixin but multiple tickers were created.

A SingleTickerProviderStateMixin can only be used as a TickerProvider once.

If a State is used for multiple AnimationController objects, or if it is passed to other objects and those objects might use it more than one time in 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This error is in your login page code where you are showing '${Coaching_name[i]}' but the variable Coaching_name is null before the data is fetched and you are trying to call the second index of a null variable. One of the simple way is change the code from

Text('${Coaching_name[i]})'

to

Text(Coaching_name == null ? "" : Coaching_name[i])

EDIT 1

Yes, the solution provide above is just a simple way for error handling. I'm just letting you to know which part of your code went wrong. The widget is rendered before data is fetched. So you need to put a loading screen while fetching data. there are few ways that you may refer.

  1. Use FutureBuilder. You may click here for example.
  2. Use pull_to_refresh plugin
  3. Use any state management eg. Provider

Personally preferred to use state management to keep the code clean. But if you're still new in flutter you may go for FutureBuilder and apply on every page that you are fetching data from back end.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...