Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 如何获取页面未被处理_Flutter - Fatal编程技术网

Flutter 如何获取页面未被处理

Flutter 如何获取页面未被处理,flutter,Flutter,我有一个应用程序,它有使用位置的mappage class _MapPageState extends State<MapPage> { LocationData currentLocation; Location _locationService = new Location(); @override void initState(){ super.initState();

我有一个应用程序,它有使用位置的mappage

class _MapPageState extends State<MapPage> {
  LocationData currentLocation;  
  Location _locationService = new Location();   
  @override
  void initState(){
    super.initState();                                                
    _locationService.onLocationChanged().listen((LocationData result) async { 
      setState(() {       
        print(result.latitude);
        print(result.longitude);                                                  
        currentLocation = result;                                             
      });                                                                     
    });  
  }
所以,我有两个想法

  • 释放页面时,删除
    onLocationChanged()
    侦听器

  • 检查在
    setState()之前是否已释放
    状态


  • 如何解决此问题???

    您可以复制粘贴下面的两个文件,并直接替换官方示例的代码

    导航到
    ListenLocationWidget
    页面后, 您可以在
    dispose()

    代码片段

    class _MyHomePageState
    ...
       RaisedButton(
          child: Text('Open route'),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute<void>(
                  builder: (context) => ListenLocationWidget()),
            );
          },
        ),
        PermissionStatusWidget(),
        Divider(height: 32),
        ServiceEnabledWidget(),
        Divider(height: 32),
        GetLocationWidget(),
        Divider(height: 32),
        //ListenLocationWidget()
    
    
    class _ListenLocationState extends State<ListenLocationWidget> {
    ...
    StreamSubscription<LocationData> _locationSubscription;
      String _error;
    
      @override
      void initState() {
        print("initState");
        super.initState();
        _listenLocation();
      }
    
      @override
      void dispose() {
        print("stopListen");
        _stopListen();
        super.dispose();
      }
      
      Future<void> _listenLocation() async {
        _locationSubscription =
            location.onLocationChanged.handleError((dynamic err) {
          setState(() {
            _error = err.code;
          });
          _locationSubscription.cancel();
        }).listen((LocationData currentLocation) {
          setState(() {
            print("setState");
            _error = null;
    
            _location = currentLocation;
          });
        });
      }
    
      Future<void> _stopListen() async {
        _locationSubscription.cancel();
      }
    
    完整代码
    main.dart

    import 'package:flutter/material.dart';
    import 'package:location/location.dart';
    import 'package:url_launcher/url_launcher.dart';
    
    import 'get_location.dart';
    import 'listen_location.dart';
    import 'permission_status.dart';
    import 'service_enabled.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Location',
          theme: ThemeData(
            primarySwatch: Colors.amber,
          ),
          home: const MyHomePage(title: 'Flutter Location Demo'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({Key key, this.title}) : super(key: key);
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      final Location location = Location();
    
      Future<void> _showInfoDialog() {
        return showDialog<void>(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('Demo Application'),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    const Text('Created by Guillaume Bernos'),
                    InkWell(
                      child: Text(
                        'https://github.com/Lyokone/flutterlocation',
                        style: TextStyle(
                          decoration: TextDecoration.underline,
                        ),
                      ),
                      onTap: () =>
                          launch('https://github.com/Lyokone/flutterlocation'),
                    ),
                  ],
                ),
              ),
              actions: <Widget>[
                FlatButton(
                  child: const Text('Ok'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
            actions: <Widget>[
              IconButton(
                icon: Icon(Icons.info_outline),
                onPressed: _showInfoDialog,
              )
            ],
          ),
          body: Container(
            padding: const EdgeInsets.all(32),
            child: Column(
              children: <Widget>[
                RaisedButton(
                  child: Text('Open route'),
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute<void>(
                          builder: (context) => ListenLocationWidget()),
                    );
                  },
                ),
                PermissionStatusWidget(),
                Divider(height: 32),
                ServiceEnabledWidget(),
                Divider(height: 32),
                GetLocationWidget(),
                Divider(height: 32),
                //ListenLocationWidget()
              ],
            ),
          ),
        );
      }
    }
    
    导入“包装:颤振/材料.省道”;
    导入“package:location/location.dart”;
    导入“package:url_launcher/url_launcher.dart”;
    导入“get_location.dart”;
    导入“listen_location.dart”;
    导入“permission_status.dart”;
    导入'service_enabled.dart';
    void main()=>runApp(MyApp());
    类MyApp扩展了无状态小部件{
    //此小部件是应用程序的根。
    @凌驾
    小部件构建(构建上下文){
    返回材料PP(
    标题:“颤振位置”,
    主题:主题数据(
    主样本:颜色。琥珀色,
    ),
    主页:const MyHomePage(标题:“颤振位置演示”),
    );
    }
    }
    类MyHomePage扩展StatefulWidget{
    constMyHomepage({Key,this.title}):super(Key:Key);
    最后的字符串标题;
    @凌驾
    _MyHomePageState createState()=>\u MyHomePageState();
    }
    类_MyHomePageState扩展状态{
    最终位置=位置();
    未来(showInfoDialog){
    返回显示对话框(
    上下文:上下文,
    生成器:(BuildContext上下文){
    返回警报对话框(
    标题:常量文本(“演示应用程序”),
    内容:SingleChildScrollView(
    子:列表体(
    儿童:[
    常量文本(“由Guillaume Bernos创建”),
    墨水池(
    子:文本(
    'https://github.com/Lyokone/flutterlocation',
    样式:TextStyle(
    装饰:textEdition.underline,
    ),
    ),
    onTap:()=>
    发射('https://github.com/Lyokone/flutterlocation'),
    ),
    ],
    ),
    ),
    行动:[
    扁平按钮(
    子项:常量文本('Ok'),
    已按下:(){
    Navigator.of(context.pop();
    },
    ),
    ],
    );
    },
    );
    }
    @凌驾
    小部件构建(构建上下文){
    返回脚手架(
    appBar:appBar(
    标题:文本(widget.title),
    行动:[
    图标按钮(
    图标:图标(Icons.info\u轮廓),
    按下按钮:\u showInfoDialog,
    )
    ],
    ),
    主体:容器(
    填充:常量边集。全部(32),
    子:列(
    儿童:[
    升起的按钮(
    子项:文本(“开放路线”),
    已按下:(){
    导航器。推(
    上下文
    材料路线(
    生成器:(上下文)=>ListenLocationWidget()),
    );
    },
    ),
    PermissionStatusWidget(),
    分隔器(高度:32),
    ServiceEnabledWidget(),
    分隔器(高度:32),
    GetLocationWidget(),
    分隔器(高度:32),
    //ListenLocationWidget()
    ],
    ),
    ),
    );
    }
    }
    
    这是否回答了您的问题?非常感谢你。我测试了工作演示。我从对您的代码进行大引用开始。
    import 'dart:async';
    
    import 'package:flutter/material.dart';
    import 'package:location/location.dart';
    
    class ListenLocationWidget extends StatefulWidget {
      const ListenLocationWidget({Key key}) : super(key: key);
    
      @override
      _ListenLocationState createState() => _ListenLocationState();
    }
    
    class _ListenLocationState extends State<ListenLocationWidget> {
      final Location location = Location();
    
      LocationData _location;
      StreamSubscription<LocationData> _locationSubscription;
      String _error;
    
      @override
      void initState() {
        print("initState");
        super.initState();
        _listenLocation();
      }
    
      @override
      void dispose() {
        print("stopListen");
        _stopListen();
        super.dispose();
      }
      
      Future<void> _listenLocation() async {
        _locationSubscription =
            location.onLocationChanged.handleError((dynamic err) {
          setState(() {
            _error = err.code;
          });
          _locationSubscription.cancel();
        }).listen((LocationData currentLocation) {
          setState(() {
            print("setState");
            _error = null;
    
            _location = currentLocation;
          });
        });
      }
    
      Future<void> _stopListen() async {
        _locationSubscription.cancel();
      }
    
      @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: Container(
            color: Colors.white,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  'Listen location: ' + (_error ?? '${_location ?? "unknown"}'),
                  style: Theme.of(context).textTheme.body2,
                ),
                Row(
                  children: <Widget>[
                    Container(
                      margin: const EdgeInsets.only(right: 42),
                      child: RaisedButton(
                        child: const Text('Listen'),
                        onPressed: _listenLocation,
                      ),
                    ),
                    RaisedButton(
                      child: const Text('Stop'),
                      onPressed: _stopListen,
                    )
                  ],
                ),
              ],
            ),
          ),
        );
      }
    }
    
    import 'package:flutter/material.dart';
    import 'package:location/location.dart';
    import 'package:url_launcher/url_launcher.dart';
    
    import 'get_location.dart';
    import 'listen_location.dart';
    import 'permission_status.dart';
    import 'service_enabled.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Location',
          theme: ThemeData(
            primarySwatch: Colors.amber,
          ),
          home: const MyHomePage(title: 'Flutter Location Demo'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({Key key, this.title}) : super(key: key);
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      final Location location = Location();
    
      Future<void> _showInfoDialog() {
        return showDialog<void>(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('Demo Application'),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    const Text('Created by Guillaume Bernos'),
                    InkWell(
                      child: Text(
                        'https://github.com/Lyokone/flutterlocation',
                        style: TextStyle(
                          decoration: TextDecoration.underline,
                        ),
                      ),
                      onTap: () =>
                          launch('https://github.com/Lyokone/flutterlocation'),
                    ),
                  ],
                ),
              ),
              actions: <Widget>[
                FlatButton(
                  child: const Text('Ok'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
            actions: <Widget>[
              IconButton(
                icon: Icon(Icons.info_outline),
                onPressed: _showInfoDialog,
              )
            ],
          ),
          body: Container(
            padding: const EdgeInsets.all(32),
            child: Column(
              children: <Widget>[
                RaisedButton(
                  child: Text('Open route'),
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute<void>(
                          builder: (context) => ListenLocationWidget()),
                    );
                  },
                ),
                PermissionStatusWidget(),
                Divider(height: 32),
                ServiceEnabledWidget(),
                Divider(height: 32),
                GetLocationWidget(),
                Divider(height: 32),
                //ListenLocationWidget()
              ],
            ),
          ),
        );
      }
    }