Flutter 提供程序错误:未处理的异常:NoSuchMethodError:在 null 上调用了 getter 'owner'

时间:2021-03-27 05:35:55

标签: android flutter dart flutter-provider

我正在使用 Flutter 构建一个应用程序。将用户注册数据发布到数据库中,并且登录后进展顺利。但是在仪表板上我根本无法发布数据。

My Emulator

我的页面表单:

final GlobalKey<FormState> _formKey = GlobalKey<FormState>();


class MainScreen4 extends StatelessWidget {
  final BuildContext menuScreenContext;
  final Function onScreenHideButtonPressed;
  final bool hideStatus;

  String message;

  BuildContext context;

  Future<void> send() async {
    _formKey.currentState.save();
    print("field: $message");
    Provider.of<SavingProvider>(context, listen: false)
        .storeMessage(message)
        .then((res) {
      if (res != null) {
        print('Success');
      } else {
        print('Failed');
      }
    });
  }

  MainScreen4(
      {Key key,
      this.menuScreenContext,
      this.onScreenHideButtonPressed,
      this.hideStatus = false})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey.shade300,
      appBar: AppBar(
        centerTitle: true,
        title: const Text('Pesan'),
      ),
      body: Stack(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(bottom: 50),
            margin: EdgeInsets.all(10),
            child: FutureBuilder(
              future: Provider.of<SavingProvider>(context, listen: false)
                  .customerMessage(),
              builder: (context, snapshot) {
                return Consumer<SavingProvider>(
                  builder: (context, data, _) {
                    return ListView.builder(
                      itemCount: data.dataMessage.length,
                      shrinkWrap: true,
                      padding: EdgeInsets.only(top: 10, bottom: 10),
                      //physics: NeverScrollableScrollPhysics(),
                      itemBuilder: (context, m) {
                        return Container(
                          padding: EdgeInsets.only(
                              left: 14, right: 14, top: 10, bottom: 10),
                          child: Align(
                            alignment: (data.dataMessage[m].sender == "bank"
                                ? Alignment.topLeft
                                : Alignment.topRight),
                            child: Container(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(20),
                                color: (data.dataMessage[m].sender == "bank"
                                    ? Colors.grey.shade200
                                    : Colors.blue[200]),
                              ),
                              padding: EdgeInsets.all(16),
                              child: ListTile(
                                title: Text('${data.dataMessage[m].message}',
                                    style: TextStyle(
                                        fontSize: 14, color: Colors.black),
                                    textAlign: TextAlign.left),
                                subtitle: Text(
                                    '${data.dataMessage[m].createdAt}',
                                    style: TextStyle(color: Colors.grey[700]),
                                    textAlign: TextAlign.left),
                              ),
                            ),
                          ),
                        );
                      },
                    );
                  },
                );
              },
            ),
          ),
          Align(
            alignment: Alignment.bottomLeft,
            child: Container(
              padding: EdgeInsets.only(left: 10, bottom: 10, top: 10),
              height: 60,
              width: double.infinity,
              color: Colors.white,
              child: Form(
                key: _formKey,
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: TextFormField(
                        onSaved: (value) => message = value,
                        decoration: InputDecoration(
                            hintText: "Write something...",
                            hintStyle: TextStyle(color: Colors.black54),
                            border: InputBorder.none),
                        validator: (value) =>
                            value.isEmpty ? "Required" : null,
                      ),
                    ),
                    SizedBox(
                      width: 15,
                    ),
                    FloatingActionButton(
                      onPressed: () {
                        send();
                      },
                      child: Icon(
                        Icons.send,
                        color: Colors.white,
                        size: 18,
                      ),
                      backgroundColor: Colors.blue,
                      elevation: 0,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

我的提供商:

// Store Message
  Future<Map<String, dynamic>> storeMessage(String message) async {
    String myId = await getId();
    final url = ApiUrl.customerMessageStore;
    print(url);
    print(message);
    final response = await http
        .post(Uri.parse(url), body: {'customer_id': myId, 'message': message});
    print('Response code: ${response.statusCode}');
    final result = json.decode(response.body);
    var dataResponse;
    if (response.statusCode == 201) {
      notifyListeners();
      dataResponse = {
        'type': 'success',
        'title': 'Sent',
        'message': result['message']
      };
      return dataResponse;
    }
    dataResponse = {
      'type': 'error',
      'title': 'Failed',
      'message': 'Server Error di Provider'
    };
    return dataResponse;
  }

命令提示符控制台:

E/flutter ( 4700): Tried calling: owner
E/flutter ( 4700): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter ( 4700): #1      Provider.of (package:provider/src/provider.dart:265:15)
E/flutter ( 4700): #2      MainScreen4.send (package:trashbank/pages/screens.dart:401:14)
E/flutter ( 4700): #3      MainScreen4.build.<anonymous closure> (package:trashbank/pages/screens.dart:507:25)
E/flutter ( 4700): #4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:994:20)
E/flutter ( 4700): #5      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter ( 4700): #6      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:607:11)
E/flutter ( 4700): #7      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
E/flutter ( 4700): #8      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:230:7)
E/flutter ( 4700): #9      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9)
E/flutter ( 4700): #10     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:93:12)
E/flutter ( 4700): #11     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:138:9)
E/flutter ( 4700): #12     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
E/flutter ( 4700): #13     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:136:18)
E/flutter ( 4700): #14     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:122:7)
E/flutter ( 4700): #15     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
E/flutter ( 4700): #16     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
E/flutter ( 4700): #17     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:288:11)
E/flutter ( 4700): #18     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
E/flutter ( 4700): #19     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
E/flutter ( 4700): #20     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
E/flutter ( 4700): #21     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
E/flutter ( 4700): #22     _rootRunUnary (dart:async/zone.dart:1370:13)
E/flutter ( 4700): #23     _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter ( 4700): #24     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter ( 4700): #25     _invoke1 (dart:ui/hooks.dart:186:10)
E/flutter ( 4700): #26     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:282:7)
E/flutter ( 4700): #27     _dispatchPointerDataPacket (dart:ui/hooks.dart:96:31)

我不明白“所有者”是什么意思。请帮助它运行良好。谢谢。

1 个答案:

答案 0 :(得分:0)

你有这个代码:

BuildContext context;

Future<void> send() async {
  _formKey.currentState.save();
  print("field: $message");
  Provider.of<SavingProvider>(context, listen: false)
      .storeMessage(message)
      .then((res) {

但是您的变量 context 未初始化。您可以在 send() 方法中移动 build 函数,或者在 context 方法中初始化变量 build,例如

Widget build(BuildContext ctx) {
  context = ctx;

或者您可以将上下文作为参数传递给 send 方法 - 这是我的首选方法:

Future<void> send(BuildContext context) async {

错误信息:

E/flutter ( 4700): Tried calling: owner
E/flutter ( 4700): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter ( 4700): #1      Provider.of (package:provider/src/provider.dart:265:15)

告诉您在文件 provider.dart 的第 265 行,方法 Provider.of 调用了一个未找到的方法 owner。查看源代码,您将看到它指的是 context.owner。问题是 context 为空。