Flutter: NoSuchMethodError : 方法 'fetchByID' 在 null 上被调用。接收方:null 尝试调用:fetchByID(2)

标签 flutter dart error-handling nosuchmethoderror nosuchmethod

我是 Flutter 的新手,这是我的第一个项目。
我正在尝试使用参数导航到新站点。该参数被接受,但我的类 notizList 中的函数返回错误消息。

我知道我的问题在于:
Notiz notiz = key.currentState.fetchByID(widget.notizID);
错误信息是:

The method 'fetchByID' was called on null.
Receiver: null
Tried calling: fetchByID(2)

这些是相关文件。

应用程序.dart
import 'style.dart';
import 'package:my_new_test_app/style.dart';
import 'Screens/home_screen.dart';
import 'Screens/notiz_detail.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      onGenerateRoute: _routes(),
      title: 'Notice',
      theme: _theme(),
    );
  }
}

ThemeData _theme() {
  return ThemeData(
    primaryColor: Colors.white,
  appBarTheme: AppBarTheme(
    textTheme : TextTheme(headline6: AppBarTextStyle)),
  textTheme: TextTheme(
  bodyText2: Body1Style,
  headline6: Title1Sytle),
);
}

RouteFactory _routes(){
  return(settings){
    final Map<String, dynamic> args = settings.arguments;
    Widget screen;
    switch (settings.name){
      case '/':
        screen = Test();
        return MaterialPageRoute(builder: (BuildContext context) => screen);
        break;
      case '/detailNotiz':
        screen = DetailNotiz(notizID: args['id']);
        return MaterialPageRoute(builder: (BuildContext context) => screen);
        break;
      default:
        return null;
    }
  };
}


notiz_detail.dart(问题出在哪里)
import 'package:my_new_test_app/models/notiz.dart';
import '../Widgets/detail_notiz_widget.dart';
import '../models/notizList.dart';


class DetailNotiz extends StatefulWidget {
const DetailNotiz({Key key, @required this.notizID}) : super(key: key);
final int notizID;

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


class _DetailNotizState extends State<DetailNotiz> {

  final GlobalKey<NotizListeState> key = GlobalKey<NotizListeState>();
  @override
  Widget build(BuildContext context) {
    Notiz notiz = key.currentState.fetchByID(widget.notizID);
    return Scaffold(
      appBar: 
        AppBar(
          centerTitle: true,
          title: Text(notiz.user+' am '+notiz.date)
          ),
        body:Container(
      child: FullNotiz(notiz.title, notiz.body),
    ),
    );
  }
}


notizList.dart
import 'package:flutter/material.dart';
import 'notiz.dart';
import '../Widgets/little_notiz_widget.dart';


class NotizListe extends StatefulWidget {

  NotizListe({Key key}) : super(key: key);
  @override
  NotizListeState createState() => NotizListeState();
}


class NotizListeState extends State<NotizListe> {

static List<Notiz> notizList =[
      Notiz(
      1,
      'USer', 
      "Title",
      "BOdy",
      "01.05.2020"
      ),
      Notiz(
       2,
       'USer', 
      "Title",
      "BOdy",
       "03.05.2020"
      ),
      Notiz(
       3,
       'USer', 
      "Title",
      "BOdy",
       "03.05.2020"
      ),
      Notiz(
       4,
       'USer', 
      "Title",
      "BOdy",
       "04.05.2020"
      ),
      Notiz(
       5,
       'USer', 
      "Title",
      "BOdy",
       "04.05.2020"
      ),

    ];


  void addToList(String title, String body){
    int index = notizList.length +1;
    Notiz element = Notiz(index, 'Marc', title, body, '05.05.2020');
    notizList.add(element);
  }

  Notiz fetchByID(int notizID){
    print('Die Länge der notiz Liste: '+ notizList.length.toString());
    print(notizID);
    for (var i = 0; i<notizList.length;i++){
      if(notizList[i].id == notizID){
        return notizList[i];
      }
    }
    return notizList[1];
  }

  @override
  Widget build(BuildContext context) {
    return notizenListView(context, notizList);
  }

  Widget notizenListView(BuildContext context, List<Notiz> notizList){
    return ListView.builder(
      itemCount: notizList.length,
      itemBuilder: (context, index) => 
          _itemBuilder(context, notizList[index]),
      );
  }
}



_onNotizTap(BuildContext context, int notizenId){
  Navigator.pushNamed(context,  '/detailNotiz', arguments: {"id": notizenId});
}

  Widget _itemBuilder(BuildContext context, Notiz notizen){

    return GestureDetector(
      onTap: ()=>_onNotizTap(context, notizen.id),
      key: Key('notizen_list_item_${notizen.id}'),
      child: Container(
        child: LittleNotiz(notizen.title, notizen.body),
      )
    );
  }



谢谢你的帮助。

最佳答案

您没有在 _DetailNotizState 中调用 NotizListeState,这就是您收到错误的原因。

由于您没有使用 NotizListeState,因此您无法将 key 传递给 NotizListe,因为您会收到此错误。

此外,在没有调用 build 方法之前,您不能使用 key,因为它不会将 key 分配给该小部件。

完整代码演示:

class DeleteWidget extends StatefulWidget {
  @override
  _DeleteWidgetState createState() => _DeleteWidgetState();
}

class _DeleteWidgetState extends State<DeleteWidget> {
  hi() {
    key.currentState.callme();
  }

  final GlobalKey<Home1State> key = GlobalKey<Home1State>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Column(
          children: [
            RaisedButton(
              onPressed: hi,
              child: Text("hello"),
            ),
            Home1(
              key: key,
            ),
          ],
        ),
      ),
    );
  }
}

class Home1 extends StatefulWidget {
  Home1({Key key}) : super(key: key);
  @override
  Home1State createState() => Home1State();
}

class Home1State extends State<Home1> {
  callme() {
    print("object");
  }

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

关于Flutter: NoSuchMethodError : 方法 'fetchByID' 在 null 上被调用。接收方:null 尝试调用:fetchByID(2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61635005/

相关文章:

c# - 获取堆栈跟踪中的参数值

javascript - react -将Promise与Edge一起使用时无法解析错误

ios - Flutter iOS-在模拟器上运行的应用无法部署到iphone-未找到-lFirebaseCore的库

flutter - 在 Flutter 中禁用 `semantics` 系统?

dart - 相当于 Dash 中的 c# EventHandler?

Flutter:光滑的圆角

Flutter 提升按钮 - 如何使用 MaterialStateProperty.all 移除提升?

android - Flutter:无法解析com.android.support:support-v4:27.1.0

flutter - 使用Text Overflow.ellipsis时如何删除文本右侧的多余空间

error-handling - 没有这样的操作: HTTP GET PATH_INFO:/services/EchoUMO