1. 程式人生 > 其它 >Flutter中使用Provider出現 Class ‘StatelessElement‘ has no instance method ‘read‘.

Flutter中使用Provider出現 Class ‘StatelessElement‘ has no instance method ‘read‘.

技術標籤:flutter

在專案中使用Provider時候出現了,文末有解決方式,問題程式碼如下:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Material App Bar'),
        ),
        body: Provider(
          create: (_)=>'測試內容111111',
          child: Builder(
            builder: (context){
              return RaisedButton(
                onPressed: (){
                  String result = context.read<String>();
                  print('YM--test4--000-->引數型別:${context.runtimeType}');
                  print('YM--test4--000-->引數型別的hashCode:${context.hashCode}');
                  print('YM--test4-0000-->獲取的結果:$result');
                  test(context);
                },
                child: Text('點我'),
              );
            },
          ),
        ),
      ),
    );
  }

  test(context){
    print('YM--test4--111-->引數型別:${context.runtimeType}');
    print('YM--test4--111-->引數型別的hashCode:${context.hashCode}');
    String result = context.read<String>();
    print('YM--test4--111-->獲取的結果:$result');
  }
  
  // test(BuildContext context){
  //   print('YM--test4--111-->引數型別:${context.runtimeType}');
  //   print('YM--test4--111-->引數型別的hashCode:${context.hashCode}');
  //   String result = context.read<String>();
  //   print('YM--test4--111-->獲取的結果:$result');
  // }
  
}

以上程式碼的runtimeTypehashCode均一致。註釋的程式碼即為解決方式。嗯…,暫時的解決是平時寫程式碼需要明確型別。

這裡嘗試分析一下原因:
1、首先Builder類裡面的屬性builder函式表面上沒定義型別,但是其實已經定義了,這裡檢視原始碼如下:
在這裡插入圖片描述
在這裡插入圖片描述
可以看到型別是BuildContext
2、其次看我們定義的test(context)函式,這裡沒寫型別,所以這裡大膽猜測下,省略掉的可能是dynamic.該欄位會在執行期間對型別進行檢查,編譯期間不會檢查,因此在編譯期間read()函式其實是沒有生成,所以在執行時候這個也調不到

上述結論不一定對,因為後續根據這個方式進行測試,發現沒有出現意料之中的錯誤…