该方法在颤振中被调用为 null

时间:2020-12-30 05:05:40

标签: api flutter error-handling flutter-layout

向大家问好, 我陷入了从后端获取数据的情况,但最初在应用程序启动之前,错误显示在手机上。 下面是错误的图像。

enter image description here

显示此内容后,应用程序将启动。我该如何处理这个错误?我尝试了旋转套件,但它不起作用。 我想在控制台上显示这个。 以下是代码-:

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(),
      ),
    );
  }
}

我能想办法处理这件事吗?

这是控制台上显示的异常 -:

 ════════ 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 total, then instead of mixing in a SingleTickerProviderStateMixin, use a regular TickerProviderStateMixin.

The relevant error-causing widget was: 
  LoginPage file:///C:/Users/PALAK/AndroidStudioProjects/education/lib/main.dart:35:7
When the exception was thrown, this was the stack: 
#0      SingleTickerProviderStateMixin.createTicker.<anonymous closure> (package:flutter/src/widgets/ticker_provider.dart:121:7)
#1      SingleTickerProviderStateMixin.createTicker (package:flutter/src/widgets/ticker_provider.dart:130:6)
#2      new AnimationController (package:flutter/src/animation/animation_controller.dart:248:21)
#3      LoginPageState.build (package:education/LogIn_SignUp/Log_In.dart:250:21)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28) 

下面是登录页面的代码-:

import 'package:education/Screens/Home_View.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:form_field_validator/form_field_validator.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

import 'SignUp.dart';


class LoginPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return LoginPageState();
  }
}


class LoginPageState extends State<LoginPage>with SingleTickerProviderStateMixin {

  bool isLoading = false;


  GlobalKey<FormState> formkey = GlobalKey<FormState>();
  final FocusNode focusNode = new FocusNode();


  var usermail, password, C_id;

  TextEditingController userEmail1 = new TextEditingController();
  TextEditingController userPassword1= new TextEditingController();



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

  var Coaching_name, Coaching_id;
  var data;

  Future<http.Request> getData() async
  {
    var client = new http.Client();
    final response = await client.get('http://192.168.0.104:5000/coaching_detail');
    final responseJson = json.decode(response.body);
      if(responseJson == null) {
        setState(() {
          Container(
            color: Colors.white,
              child: isLoading ? SpinKitSquareCircle(
                color: Colors.red,
                size: 50.0,
                controller: AnimationController(vsync: this,duration: const Duration(seconds: 3)),
              ): Container(height: 200,)
              //isLoading == true ? Text('Loading ...') : Text('Loading ...'),
          );
        });
      }
      else {
        setState(() {
          dynamic coaching_id = responseJson['coachid'];
          dynamic coaching_name = responseJson['coachname'];

          Coaching_name = coaching_name;
          Coaching_id = coaching_id;
          data = responseJson;
        });
      }


    print(responseJson);
    client.close();
  }


  int i = 2;



  Future signInWithUserNameAndPassword(String email, String Password, String coachid) async {

    try {
      final http.Response response = await http.post(
        'http://192.168.0.104:5000/user_login',
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode(<String, String>{
          'useremail': email,
          'userpassword': Password,
          'coachid' : coachid,
        }),
      );
      final responseJson = json.decode(response.body);

      print(responseJson);



      if (responseJson['coach_id'] != null) {
        print('success');
        print(responseJson);

            setState(() {
              dynamic user_id = responseJson['userid'];
              dynamic user_name = responseJson['user_name'];
              dynamic mobile_number = responseJson['mobile_number'];
              dynamic user_address = responseJson['user_address'];
              dynamic coaching_id = responseJson['coach_id'];
              dynamic coach_name = responseJson['coach_name'];
              dynamic coach_address = responseJson['coach_address'];
              dynamic primary_no = responseJson['primary_no'];
              dynamic alt_number = responseJson['alt_number'];
              dynamic coaching_email = responseJson['coaching_email'];


              userid = user_id;
              username = user_name;
              mobilenumber = mobile_number;
              useraddress = user_address;
              coachingid = coaching_id;
              coachingname = coach_name;
              coachingaddress = coach_address;
              primaryno = primary_no;
              altno = alt_number;
              coachingemail = coaching_email;

            });


        Navigator.pushReplacement(context, MaterialPageRoute(
          builder: (context) => homeView(
              user_id: userid, user_name:username, mobile_number:mobilenumber, user_address:useraddress,
              coaching_id:coachingid, coaching_name:coachingname, coaching_address:coachingaddress,
              primary_no:primaryno, altnumber:altno, coaching_email:coachingemail, user_Email:usermail,

          ),
        ));
      }
      else{
        print('fail');
        showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text("Error"),
                content: Text("Incorrect Credentials"),
                actions: [
                  FlatButton(
                    child: Text("Ok"),
                    onPressed: () {
                      Navigator.pushReplacement(context, MaterialPageRoute(
                          builder: (context)=> LoginPage()
                      ));
                    },
                  )
                ],
              );
            });
      }
    }
    catch (e) {
      print(e.toString());
    }
  }

  signIn(){
    if(formkey.currentState.validate()){
      setState(() {
        isLoading = true;
      });
      usermail = userEmail1.text;
      password = userPassword1.text;
      C_id = Coaching_id[i].toString();

      signInWithUserNameAndPassword(usermail, password, C_id);
     
    }
  }



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


  @override
  void dispose(){
    userEmail1.dispose();
    userPassword1.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery
        .of(context)
        .size
        .height;
    double width = MediaQuery
        .of(context)
        .size
        .width;
    return Scaffold(
      body: isLoading ? SpinKitSquareCircle(
        color: Colors.red,
        size: 50.0,
        controller: AnimationController(vsync: this,duration: const Duration(seconds: 3)),
      )
          : Center(
        child: SingleChildScrollView(
          child: Form(
            key: formkey,
            // autovalidate: true,
            child: Column(
              children: <Widget>[
                Container(
                  width: width,
                  height: height,
                  padding: const EdgeInsets.all(16.0),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Colors.lightBlueAccent, Colors.blueAccent],
                    ),
                  ),
                  child: Column(
                    children: <Widget>[
                      Container(
                        margin: const EdgeInsets.only(top: 40.0, bottom: 20.0),
                        height: 50,
                      ),
                      Text(
                        '${Coaching_name[i]}',
                        style: TextStyle(
                          fontSize: 45.0,
                          letterSpacing: 4.5,
                          fontFamily: 'Sarif',
                          fontWeight: FontWeight.w300,
                          color: Colors.white,
                        ),
                      ),

                      SizedBox(height: 130.0),
                      TextFormField(
                        controller: userEmail1,
                        decoration: InputDecoration(
                          contentPadding: const EdgeInsets.all(16.0),
                          prefixIcon: Container(
                              padding:
                              const EdgeInsets.only(top: 16.0, bottom: 16.0),
                              margin: const EdgeInsets.only(right: 8.0),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                 ),
                              child: Icon(
                                Icons.person,
                                color: Colors.purpleAccent,
                              )),
                          hintText: "enter your email",
                          hintStyle: TextStyle(color: Colors.white54),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(30.0),
                              borderSide: BorderSide.none),
                          filled: true,
                          fillColor: Colors.white.withOpacity(0.1),
                        ),
                        validator: MultiValidator(
                            [
                              RequiredValidator(errorText: 'Required'),
                              // EmailValidator(errorText: 'not a valid Email'),
                            ]
                        ),
                        onSaved: (user) => usermail(user),
                      ),


                      SizedBox(height: 20.0),
                      TextFormField(
                        controller: userPassword1,
                        decoration: InputDecoration(
                          contentPadding: const EdgeInsets.all(16.0),
                          prefixIcon: Container(
                              padding:
                              const EdgeInsets.only(top: 16.0, bottom: 16.0),
                              margin: const EdgeInsets.only(right: 8.0),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                              ),
                              child: Icon(
                                Icons.lock,
                                color: Colors.purpleAccent,
                              )),

                          hintText: "enter your password",
                          hintStyle: TextStyle(color: Colors.white54),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(30.0),
                              borderSide: BorderSide.none),
                          filled: true,
                          fillColor: Colors.white.withOpacity(0.1),
                        ),
                        obscureText: true,
                        validator: MultiValidator(
                            [
                              MinLengthValidator(4,
                                  errorText: 'should be atleast 6 characters'),
                              MaxLengthValidator(10,
                                  errorText: 'should not be more than 10 characters'),
                              RequiredValidator(errorText: 'Required'),
                            ]
                        ),
                      ),


                      SizedBox(height: 30.0),
                      SizedBox(
                        width: double.infinity,
                        child: RaisedButton(
                          color: Colors.white,
                          textColor: Colors.purpleAccent,
                          padding: const EdgeInsets.all(20.0),
                          child: Text("Login".toUpperCase()),
                          onPressed: () {
                            NavigationMode.directional;
                            signIn();
                          },
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(30.0)
                          ),
                        ),
                      ),



                      SizedBox(height: 25,),
                      Align(
                        alignment: Alignment.bottomCenter,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: <Widget>[
                            SizedBox(height: 20,),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Text("Don\'t have an account?",
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 18,
                                  ),
                                ),
                                FlatButton(
                                  child: Text("Sign in",
                                    style: TextStyle(
                                      color: Colors.amberAccent,
                                      fontSize: 18,
                                    ),
                                  ),
                                  textColor: Colors.indigo,
                                  onPressed: (){

                                    Navigator.pushReplacement(context, MaterialPageRoute(
                                        builder: (context) => signUp()
                                    ));
                                  },
                                )
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

此错误出现在您显示 '${Coaching_name[i]}' 的登录页面代码中,但在获取数据之前变量 Coaching_name 为空,并且您尝试调用空变量的第二个索引。一种简单的方法是从

更改代码

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

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

编辑 1

是的,上面提供的解决方案只是一种简单错误处理方式。 我只是让你知道你的代码的哪一部分出错了。在获取数据之前呈现小部件。所以你需要在获取数据时放置一个加载屏幕。 您可以参考几种方法。

  1. 使用 FutureBuilder。例如,您可以点击 here
  2. 使用 pull_to_refresh 插件
  3. 使用任何状态管理,例如。提供者

个人更喜欢使用状态管理来保持代码干净。但是,如果您还是 Flutter 新手,您可以选择 FutureBuilder 并将其应用于您从后端获取数据的每个页面。