Flutter 获取数据错误:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常:“String”类型不是“index”的“int”类型的子类型

时间:2021-02-22 14:25:11

标签: firebase flutter firebase-realtime-database

美好的一天/晚上。

我正在尝试从 firebase 实时数据库中检索一些数据,当我将用户 UID 用作子级来获取数据时出现错误。

这是它的代码

   void initState() {
DatabaseReference ref = FirebaseDatabase.instance.reference();
String userId  = (FirebaseAuth.instance.currentUser).uid;
ref.child('User').child(userId).once().then((DataSnapshot snap ){
  var keys = snap.value.keys;
  var data = snap.value;
  allData.clear();
  for(var key in keys){
    myData d = new myData(
        data[key]['Full_Name'],
        data[key]['Email'],
        data[key]['Phone_Number'],
        data[key]['Address']
    );
    allData.add(d);

  }
  setState(() {
    print('Length:${allData.length}');

  });
});
  }

对于列表

     Container(
                height: data.size.height,

                child: allData.length==0
                  ? SpinKitFadingCircle(
                    color: Colors.white,
                    size: 150.0
                )
                :new ListView.builder(
                itemBuilder: (_,index){
return Profile_UI(context,allData[index].Full_Name,allData[index].Email,allData[index].Phone_Number,allData[index].Address);
                },
                itemCount: allData.length,
              ),


              ),

这是所有的代码

class Profile extends StatefulWidget {

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

class _ProfileState extends State<Profile> {

final AuthenticationService _auth = AuthenticationService();
final FirebaseAuth auth = FirebaseAuth.instance;
User user;
  List<myData> allData = [];
@override
  // ignore: must_call_super
  void initState() {
DatabaseReference ref = FirebaseDatabase.instance.reference();
String userId  = (FirebaseAuth.instance.currentUser).uid;
ref.child('User').child(userId).once().then((DataSnapshot snap ){
  var keys = snap.value.keys;
  var data = snap.value;
  allData.clear();
  for(var key in keys){
    myData d = new myData(
        data[key]['Full_Name'],
        data[key]['Email'],
        data[key]['Phone_Number'],
        data[key]['Address']
    );
    allData.add(d);

  }
  setState(() {
    print('Length:${allData.length}');

  });
});
  }
  @override
  Widget build(BuildContext context) {

    final data = MediaQuery.of(context);
    return Scaffold(
      body: AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle.light,
        child: GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          child: Stack(
            children: <Widget>[
              Container(
                height: 600.0,
                width: data.size.width,
                child: SingleChildScrollView(
                  physics: AlwaysScrollableScrollPhysics(),
                ),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Colors.cyan[700],
                      Color(0xFF61A4F1),
                      Color(0xFF478DE0),
                      Color(0xFF398AE5),
                    ],
                    stops: [0.1, 0.4, 0.7, 0.9],
                  ),
                ),
              ),
              Container(
                height: data.size.height,

                child: allData.length==0
                  ? SpinKitFadingCircle(
                    color: Colors.white,
                    size: 150.0
                )
                :new ListView.builder(
                itemBuilder: (_,index){
return Profile_UI(context,allData[index].Full_Name,allData[index].Email,allData[index].Phone_Number,allData[index].Address);
                },
                itemCount: allData.length,
              ),


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



class _EditProfilePage extends StatefulWidget {
  @override
  __EditProfilePageState createState() => __EditProfilePageState();
}

class __EditProfilePageState extends State<_EditProfilePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        elevation: 1,
        leading: IconButton(

          icon: Icon(
            Icons.arrow_back,
            color: Colors.blueAccent,
          ),
        onPressed: (){Navigator.of(context).pop(MaterialPageRoute(builder: (context)=>MenuTry()));},
        ),
      ),
      body: Container(
        padding: EdgeInsets.only(left: 16,top: 25,right: 16),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF73AEF5),
              Colors.blue.shade300,
              Colors.blue.shade300,
              Colors.blue.shade200,
            ],
            stops: [0.1, 0.4, 0.7, 0.9],
          ),
        ),
        child: GestureDetector(
          onTap:() {FocusScope.of(context).unfocus();
          },
          child: ListView(
            children: [
              Text('Edit Profile', style: TextStyle(
                fontSize: 25, fontWeight: FontWeight.w500,
              ),
              ),

            SizedBox(
              height: 15,
            ),
            Center(
              child: Stack(
                children: [
                  Container(
                    width: 130,
                    height: 130,
                    decoration: BoxDecoration(
                      border: Border.all(
                        width: 4,
                        color: Theme.of(context).scaffoldBackgroundColor,
                      ),
                      boxShadow: [
                        BoxShadow(
                          spreadRadius: 2, blurRadius: 10,
                          color: Colors.black.withOpacity(0.1),
                          offset: Offset(0,10)
                        ),
                      ],
                      shape: BoxShape.circle,
                      image: DecorationImage(
                        fit: BoxFit.cover,
                        image : NetworkImage("https://qph.fs.quoracdn.net/main-qimg-2b21b9dd05c757fe30231fac65b504dd")
                      ),
                    ),
                  ),
                  Positioned(
                    bottom: 0,
                    right: 0,
                    child: Container(
                    height: 40,
                    width: 40,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(
                        width: 4,
                        color: Theme.of(context).scaffoldBackgroundColor,
                      ),
                      color: Colors.white
                    ),
                    child: IconButton(
                      onPressed: () => Navigator.of(context).push(MaterialPageRoute(builder: (context)=>ImagePick())),
                     icon: Icon(Icons.camera_alt,color: Colors.blueAccent),),
                  ),)
                ],
              ),
            ),
           SizedBox(
             height: 35,
           ),
           TextField(
             decoration: InputDecoration(
               contentPadding: EdgeInsets.only(bottom: 3),
               labelText: "Full Name",
               floatingLabelBehavior: FloatingLabelBehavior.always,
               hintText: "",
               hintStyle: TextStyle(
                 fontSize: 16, fontWeight: FontWeight.bold,
                 color: Colors.black,
               ),
             ),
           ),
              SizedBox(
                height: 35,
              ),
              TextField(
                decoration: InputDecoration(
                    contentPadding: EdgeInsets.only(bottom: 3),
                    labelText: "Email",
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    hintText: "",
                    hintStyle: TextStyle(
                      fontSize: 16, fontWeight: FontWeight.bold,
                      color: Colors.black,
                    ),
                ),
              ),
              SizedBox(
                height: 35,
              ),
              TextField(
                decoration: InputDecoration(
                    contentPadding: EdgeInsets.only(bottom: 3),
                    labelText: "Address",
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    hintText: "",
                    hintStyle: TextStyle(
                      fontSize: 16, fontWeight: FontWeight.bold,
                      color: Colors.black,
                    )
                ),
              ),
              SizedBox(
                height: 35,
              ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                OutlineButton(
                  color: Colors.green,
                  padding: EdgeInsets.symmetric(horizontal: 50),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                  onPressed: (){ Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=>MenuTry()));},
                  child: Text("CANCEL",style: TextStyle(
                    fontSize: 14, letterSpacing: 2.2, color: Colors.black,
                  ),),
                ),
                SizedBox(
                  height: 35,
                ),
                OutlineButton(
                  color: Colors.green,
                  padding: EdgeInsets.symmetric(horizontal: 50),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                  onPressed: (){
                    Navigator.push(context, MaterialPageRoute(builder: (context)=>ImagePick()));
                    
                  },
                  child: Text("SAVE",style: TextStyle(
                    fontSize: 14, letterSpacing: 2.2, color: Colors.black,
                  ),),
                ),

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





class AlwaysDisabledFocusNode extends FocusNode {
  @override
  bool get hasFocus => false;
}
Widget Profile_UI(BuildContext context,String Full_Name,String Email,String Phone_Number,String Address) {
  final data = MediaQuery.of(context);
  return Container(
    height: data.size.height,

    padding: EdgeInsets.symmetric(
      horizontal: 40.0,
      vertical: 40.0,
    ),
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'Profile',
          style: TextStyle(
            color: Colors.white,
            fontFamily: 'OpenSans',
            fontSize: 30.0,
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(height: 30.0),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[

            Text(
              'Your Full Name',
              style: kLabelStyle,
            ),
            SizedBox(height: 10.0),
            Container(
              alignment: Alignment.centerLeft,
              decoration: kBoxDecorationStyle,
              height: 60.0,
              child: TextFormField(
                initialValue: '$Full_Name',
                enableInteractiveSelection: false,
                focusNode: new AlwaysDisabledFocusNode(),
                keyboardType: null,
                style: TextStyle(
                  color: Colors.white,
                  fontFamily: 'OpenSans',
                ),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.only(top: 14.0),
                  prefixIcon: Icon(
                    Icons.account_box_rounded,
                    color: Colors.white,
                  ),
                  hintText: 'No Data Available',
                  hintStyle: kHintTextStyle,
                ),
              ),
            ),
          ],
        ),
        SizedBox(height: 20,),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[

            Text(
              'Your Email',
              style: kLabelStyle,
            ),
            SizedBox(height: 10.0),
            Container(
              alignment: Alignment.centerLeft,
              decoration: kBoxDecorationStyle,
              height: 60.0,
              child: TextFormField(
                initialValue: '$Email',
                enableInteractiveSelection: false,
                focusNode: new AlwaysDisabledFocusNode(),
                keyboardType: null,
                style: TextStyle(
                  color: Colors.white,
                  fontFamily: 'OpenSans',
                ),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.only(top: 14.0),
                  prefixIcon: Icon(
                    Icons.email,
                    color: Colors.white,
                  ),
                  hintText: 'No Data Available',
                  hintStyle: kHintTextStyle,
                ),
              ),
            ),
          ],
        ),
        SizedBox(height: 20,),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[

            Text(
              'Your Phone Number',
              style: kLabelStyle,
            ),
            SizedBox(height: 10.0),
            Container(
              alignment: Alignment.centerLeft,
              decoration: kBoxDecorationStyle,
              height: 60.0,
              child: TextFormField(
                initialValue: '$Phone_Number',
                enableInteractiveSelection: false,
                focusNode: new AlwaysDisabledFocusNode(),
                keyboardType: null,
                style: TextStyle(
                  color: Colors.white,
                  fontFamily: 'OpenSans',
                ),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.only(top: 14.0),
                  prefixIcon: Icon(
                    Icons.phone_android_rounded,
                    color: Colors.white,
                  ),
                  hintText: 'No Data Available',
                  hintStyle: kHintTextStyle,
                ),
              ),
            ),
          ],
        ),
        SizedBox(height: 20,),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[

            Text(
              'Your Address',
              style: kLabelStyle,
            ),
            SizedBox(height: 10.0),
            Container(
              alignment: Alignment.centerLeft,
              decoration: kBoxDecorationStyle,
              height: 60.0,
              child: TextFormField(
                initialValue: '$Address',
                enableInteractiveSelection: false,
                focusNode: new AlwaysDisabledFocusNode(),
                keyboardType: null,
                style: TextStyle(
                  color: Colors.white,
                  fontFamily: 'OpenSans',
                ),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.only(top: 14.0),
                  prefixIcon: Icon(
                    Icons.location_pin,
                    color: Colors.white,
                  ),
                  hintText: 'No Data Available',
                  hintStyle: kHintTextStyle,
                ),
              ),
            ),
          ],
        ),
      ],
    ),

  );
}

这是所有的错误日志

  W/DynamiteModule( 6389): Local module descriptor class for providerinstaller not found.
I/DynamiteModule( 6389): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller( 6389): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
W/System  ( 6389): Ignoring header X-Firebase-Locale because its value was null.
W/System  ( 6389): Ignoring header X-Firebase-Locale because its value was null.
D/FirebaseAuth( 6389): Notifying id token listeners about user ( xFM1dsh9BON1eWlIQYMQd96CI7H3 ).
E/flutter ( 6389): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
E/flutter ( 6389): #0      _ProfileState.initState.<anonymous closure> (package:mainflutter/screens/main_menu/profile.dart:40:18)
E/flutter ( 6389): #1      _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter ( 6389): #2      _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 6389): #3      _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
E/flutter ( 6389): #4      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
E/flutter ( 6389): #5      Future._propagateToListeners (dart:async/future_impl.dart:725:32)
E/flutter ( 6389): #6      Future._completeWithValue (dart:async/future_impl.dart:529:5)
E/flutter ( 6389): #7      _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:40:15)
E/flutter ( 6389): #8      _completeOnAsyncReturn (dart:async-patch/async_patch.dart:311:13)
E/flutter ( 6389): #9      Query.once (package:firebase_database/src/query.dart)
E/flutter ( 6389): <asynchronous suspension>
E/flutter ( 6389): #10     _ProfileState.initState (package:mainflutter/screens/main_menu/profile.dart:34:33)
E/flutter ( 6389): #11     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4812:57)
E/flutter ( 6389): #12     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4649:5)
E/flutter ( 6389): #13     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3615:14)
E/flutter ( 6389): #14     Element.updateChild (package:flutter/src/widgets/framework.dart:3377:20)
E/flutter ( 6389): #15     SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6171:14)
E/flutter ( 6389): #16     Element.updateChild (package:flutter/src/widgets/framework.dart:3367:15)
E/flutter ( 6389): #17     SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6171:14)
E/flutter ( 6389): #18     Element.updateChild (package:flutter/src/widgets/framework.dart:3367:15)
E/flutter ( 6389): #19     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4700:16)
E/flutter ( 6389): #20     Element.rebuild (package:flutter/src/widgets/framework.dart:4369:5)
E/flutter ( 6389): #21     StatelessElement.update (package:flutter/src/widgets/framework.dart:4756:5)
E/flutter ( 6389): #22     Element.updateChild (package:flutter/src/widgets/framework.dart:3367:15)
E/flutter ( 6389): #23     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4700:16)
E/flutter ( 6389): #24     Element.rebuild (package:flutter/src/widgets/framework.dart:4369:5)
E/flutter ( 6389): #25     StatelessElement.update (package:flutter/src/widgets/framework.dart:4756:5)
E/flutter ( 6389): #26     Element.updateChild (package:flutter/src/widgets/framework.dart:3367:15)
E/flutter ( 6389): #27     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4700:16)
E/flutter ( 6389): #28     Element.rebuild (package:flutter/src/widgets/framework.dart:4369:5)
E/flutter ( 6389): #29     ProxyElement.update (package:flutter/src/widgets/framework.dart:5033:5)
E/flutter ( 6389): #30     Element.updateChild (package:flutter/src/widgets/framework.dart:3367:15)
E/flutter ( 6389): #31     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4700:16)
E/flutter ( 6389): #32     Element.rebuild (package:flutter/src/widgets/framework.dart:4369:5)
E/flutter ( 6389): #33     ProxyElement.update (package:flutter/src/widgets/framework.dart:5033:5)
E/flutter ( 6389): #34     Element.updateChild (package:flutter/src/widgets/framework.dart:3367:15)
E/flutter ( 6389): #35     RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5693:32)
E/flutter ( 6389): #36     MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6293:17)
E/flutter ( 6389): #37     Element.updateChild (package:flutter/src/widgets/framework.dart:3367:15)
E/flutter ( 6389): #38     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4700:16)
E/flutter ( 6389): #39     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4847:11)
E/flutter ( 6389): #40     Element.rebuild (package:flutter/src/widgets/framework.dart:4369:5)
E/flutter ( 6389): #41     StatefulElement.update (package:flutter/src/widgets/framework.dart:4879:5)
E/flutter ( 6389): #42     Element.updateChild (package:flutter/src/widgets/framework.dart:3367:15)
E/flutter ( 6389): #43     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4700:16)
E/flutter ( 6389): #44     Element.rebuild (package:flutter/src/widgets/framework.dart:4369:5)
E/flutter ( 6389): #45     ProxyElement.update (package:flutter/src/widgets/framework.dart:5033:5)
E/flutter ( 6389): #46     Element.updateChild (package:flutter/src/widgets/framework.dart:3367:15)
E/flutter ( 6389): #47     Compon

任何帮助都会很可爱,谢谢。

0 个答案:

没有答案