方法'[]'在null上被调用。接收方:null尝试调用:[](0)

时间:2020-02-09 13:51:13

标签: flutter dart compiler-errors

当我尝试打开相机电源时发生此错误。我该如何解决错误。请帮助...

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building KeyedSubtree-[<0>]:

**The method '[]' was called on null.
Receiver: null
Tried calling: [](0)**

The relevant error-causing widget was: 
  TabBarView file:///C:/Users/PC/AndroidStudioProjects/flutter_app/lib/main.dart:69:38
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1      _CameraTabPageState.initState (package:flutter_app/tab_pages/camera.dart:17:42)
#2      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
#3      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
#4      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

在main.dart中

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:camera/camera.dart';

//Own page imports
import 'package:flutter_app/tab_pages/camera.dart';

List<CameraDescription> cameras;
Future<void> main() async{
  runApp(MyApp());
}


class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.red,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {


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

class _MyHomePageState extends State<MyHomePage> {
  final tabs=<Tab>[
    Tab(icon: Icon(Icons.photo_camera)),
    Tab(text: "Chats",),
    Tab(text: "Status",),
    Tab(text: "Calls",),
  ];

  final tabPages=<Widget>[
    CameraTabPage(),
    Center(child: Text("Chats"),),
    Center(child: Text("Status"),),
    Center(child: Text("Calls"),),
  ];

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      initialIndex: 1,
      length: tabs.length,
      child: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            snap: true,
            pinned: false,
            floating: true,
            title: Text("TellMe"),
            bottom: TabBar(tabs: tabs),
            actions: <Widget>[
              IconButton(icon: Icon(Icons.search, color: Colors.white,),onPressed: (){},tooltip: "Search",),
              IconButton(icon: Icon(Icons.menu, color: Colors.white),onPressed: (){},tooltip: "More options",),
            ],
          ),
          SliverFillRemaining(child: TabBarView(children: tabPages,),
          ),
        ],
      ),
    );
  }
}

在camera.dart中

import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:flutter_app/main.dart';

class CameraTabPage extends StatefulWidget {
  @override
  _CameraTabPageState createState() => _CameraTabPageState();
}

class _CameraTabPageState extends State<CameraTabPage> {
  CameraController controller;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller = CameraController(cameras[0],ResolutionPreset.medium);
    controller.initialize().then((_){
      if(!mounted){
        return;
      }
      setState((){});
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    // TODO: implement dispose
    super.dispose();

  }
  @override
  Widget build(BuildContext context) {
    if(!controller.value.isInitialized){
      return Container();
    }
    return AspectRatio(
      aspectRatio: controller.value.aspectRatio,
      child: CameraPreview(controller),
    );
  }
}

2 个答案:

答案 0 :(得分:0)

我看到了您的List相机;但是它没有在代码中的任何地方初始化。因此很明显,当您调用照相机[0]时,该应用将立即崩溃。

答案 1 :(得分:0)

再次感谢您。.添加此代码后,我已修复它

List<CameraDescription> cameras; 
Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); cameras = await availableCameras(); runApp(MyApp()); 
– Mohammad jayyousi Feb 10 at 13:34 

这对我有很大帮助