草庐IT

dart - 将小部件与状态分开

coder 2023-07-22 原文

我有下面的工作正常,用于获取当前位置并显示它:

import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:flutter/services.dart';
import 'package:simple_permissions/simple_permissions.dart';
import 'babies.dart';

class LocationState extends State {

  String _location_text;

  Location _location = new Location();
  Map<String, double> _currentLocation;

  String error;

  @override
  void initState() {
    super.initState();

    setState(() {
      _location_text = 'Clik to update location';
    });

  }

  // Platform messages are asynchronous, so we initialize in an async method.
  _getLocation() async {
    Map<String, double> location;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      await SimplePermissions.requestPermission(Permission.AccessFineLocation);
      location = await _location.getLocation();
      error = null;
    } on PlatformException catch (e) {
      if (e.code == 'PERMISSION_DENIED') {
        error = 'Permission denied';
      } else if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
        error =
        'Permission denied - please ask the user to enable it from the app settings';
      }
      location = null;
    }
    print("error $error");

    setState(() {
      _currentLocation = location;
      _location_text = ('${_currentLocation["latitude"]}, ${_currentLocation["longitude"]}' ?? 'Grant location Access');
      print(_currentLocation);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Baby Name Votes')),
      body: _buildBody(context),
    );
  }

  Widget _buildBody(BuildContext context) {
    return
      Column(
        children: <Widget>[
         Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
        child: Column(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey),
                borderRadius: BorderRadius.circular(5.0),
              ),
              child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    ButtonTheme.bar(
                        child: ButtonBar(
                            children: <Widget>[
                              Text.rich(
                                TextSpan(text: '$_location_text'),
                              ),
                              FlatButton(
                                child: const Icon(Icons.my_location),
                                onPressed: () {
                                  _getLocation();
                                  var alt = _currentLocation["latitude"];
                                  print(
                                      "my $alt at location is: $_currentLocation");
                                },
                              )
                            ])
                    ),

                  ]),
            ),
        ],
      ),
    ),
            Expanded(
            child: MyCustomListViewWidget(),
           ),
        ],
      );
  }
}

我想将小部件简化为:

  Widget _buildBody(BuildContext context) {
    return
      Column(
        children: <Widget>[
           MyLocationWidget(),
           Expanded(child: MyCustomListViewWidget(),),
        ],
      );
  }

所以,我编写了如下所示的 MyLocationWidget,但是遇到了一个问题,即对于与 state 相关的所有函数/参数,都出现了 undefined name 的错误_getLocation()$_currentLocation$_location_text:

import 'package:flutter/material.dart';
import 'location.dart';

class MyLocationWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Column(
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(5.0),
            ),
            child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  ButtonTheme.bar(
                      child: ButtonBar(
                          children: <Widget>[
                            Text.rich(
                              TextSpan(text: '$_location_text'),
                            ),
                            FlatButton(
                              child: const Icon(Icons.my_location),
                              onPressed: () {
                                _getLocation();
                                var alt = _currentLocation["latitude"];
                                print(
                                    "my $alt at location is: $_currentLocation");
                              },
                            )
                          ])
                  ),

                ]),
          ),
        ],
      ),
    );
  }
}

所以,我的问题是如何在自定义小部件中定义这些变量,以便它们与 state

顺利交换数据

最佳答案

发送点击回调的解决方案:

class MyLocationWidget extends StatelessWidget {
  MyLocationWidget(this.clickCallback);
  final VoidCallback clickCallback;

  //...

                        FlatButton(
                          child: const Icon(Icons.my_location),
                          onPressed: () {
                            clickCallback();
                          },

创建小部件 - MyLocationWidget(_getLocation)

但是对于 _currentLocation 来说会稍微困难一些。对于这种情况,我会使用 Stream

更新

考虑到 VoidCallbackTextEditingController,完整的解决方案是:

小部件:

import 'package:flutter/material.dart';

class LocationCapture extends StatelessWidget {
  LocationCapture(this.clickCallback, this.tc);
  final TextEditingController tc;
  final VoidCallback clickCallback;

  @override
  Widget build(BuildContext context) {
    return
        return Row(
  textDirection: TextDirection.rtl,  // <= This important
  children: <Widget>[
    FlatButton(
      child: const Icon(Icons.my_location),
      onPressed: () => clickCallback(),
    ),
    Expanded(child: TextField(
        controller: tc,
        enabled: false,
        textAlign: TextAlign.center,
        decoration: InputDecoration.collapsed(hintText: "")
    ))
  ],
);
  }
}

状态:

import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:flutter/services.dart';
import 'package:simple_permissions/simple_permissions.dart';
import 'package:baby_names/Widgets/babies.dart';
import 'package:baby_names/Widgets/location.dart';

class LocationState extends State {

  final myController = TextEditingController();
  Location _location = new Location();
  Map<String, double> _currentLocation;

  String error;

  _getLocation() async {
    Map<String, double> location;
    try {
      await SimplePermissions.requestPermission(Permission.AccessFineLocation);
      location = await _location.getLocation();
      error = null;
    } on PlatformException catch (e) {
      if (e.code == 'PERMISSION_DENIED') {
        error = 'Permission denied';
      } else if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
        error =
        'Permission denied - please ask the user to enable it from the app settings';
      }
      location = null;
    }
    print("error $error");

    setState(() {
      _currentLocation = location;
      update_controller(_currentLocation);
      print(_currentLocation);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Baby Name Votes')),
      body: _buildBody(context),
    );
  }

  Widget _buildBody(BuildContext context) {
    return
      Column(
        children: <Widget>[
          LocationCapture(_getLocation, myController),
          Expanded(
            child: BabiesVotes(),
          ),
        ],
      );
  }

  void update_controller(Map<String, double> currentLocation) {
    myController.text = ('${_currentLocation["latitude"]}, ${_currentLocation["longitude"]}' ?? 'Grant location Access');
  }
}

关于dart - 将小部件与状态分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53890454/

有关dart - 将小部件与状态分开的更多相关文章

  1. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  2. ruby-on-rails - 如何将验证与模型分开 - 2

    我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:

  3. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  4. ruby - 字符串文字中的转义状态作为 `String#tr` 的参数 - 2

    对于作为String#tr参数的单引号字符串文字中反斜杠的转义状态,我觉得有些神秘。你能解释一下下面三个例子之间的对比吗?我特别不明白第二个。为了避免复杂化,我在这里使用了'd',在双引号中转义时不会改变含义("\d"="d")。'\\'.tr('\\','x')#=>"x"'\\'.tr('\\d','x')#=>"\\"'\\'.tr('\\\d','x')#=>"x" 最佳答案 在tr中转义tr的第一个参数非常类似于正则表达式中的括号字符分组。您可以在表达式的开头使用^来否定匹配(替换任何不匹配的内容)并使用例如a-f来匹配一

  5. ruby - Net::HTTP 获取源代码和状态 - 2

    我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur

  6. ruby-on-rails - 为模型创建状态属性 - 2

    我想为我的Task模型创建一个status属性,该属性将按以下顺序指示它在三部分进度中的位置:打开=>进行中=>完成。它的工作方式类似于亚马逊包裹的交付方式:已订购=>已发货=>已交付。我想知道设置此属性的最佳方法是什么。我可能是错的,但创建三个独立的bool属性似乎有点多余。实现此目标的最佳方法是什么? 最佳答案 Rails4有一个内置的enummacro.它使用单个整数列并映射到键列表。classOrderenumstatus:[:ordered,:shipped,:delivered]end状态映射如下:{ordered:0,

  7. ruby - 是否可以在不实际发送或读取数据的情况下查明 ruby​​ 套接字是否处于 ESTABLISHED 或 CLOSE_WAIT 状态? - 2

    s=Socket.new(Socket::AF_INET,Socket::SOCK_STREAM,0)s.connect(Socket.pack_sockaddr_in('port','hostname'))ssl=OpenSSL::SSL::SSLSocket.new(s,sslcert)ssl.connect从这里开始,如果ssl连接和底层套接字仍然是ESTABLISHED,或者它是否在默认值7200之后进入CLOSE_WAIT,我想检查一个线程几秒钟甚至更糟的是在实际上不需要.write()或.read()的情况下关闭。是用select()、IO.select()还是其他方法完成

  8. ruby - 在 ruby​​ 中生成一个进程,捕获 stdout,stderr,获取退出状态 - 2

    我想从ruby​​rake脚本运行一个可执行文件,比如foo.exe我希望将foo.exe的STDOUT和STDERR输出直接写入我正在运行rake任务的控制台.当进程完成时,我想将退出代码捕获到一个变量中。我如何实现这一目标?我一直在玩backticks、process.spawn、system但我无法获得我想要的所有行为,只有部分更新:我在Windows上,在标准命令提示符下,而不是cygwin 最佳答案 system获取您想要的STDOUT行为。它还返回true作为零退出代码,这可能很有用。$?填充了有关最后一次system调

  9. ruby-on-rails - 状态机、模型验证和 RSpec - 2

    这是我当前的类定义和规范:classEvent:not_starteddoevent:game_starteddotransition:not_started=>:in_progressendevent:game_endeddotransition:in_progress=>:finalendevent:game_postponeddotransition[:not_started,:in_progress]=>:postponedendstate:not_started,:in_progress,:postponeddovalidate:end_time_before_finalen

  10. ruby - 如何使用 cucumber 在场景之间共享状态 - 2

    我有一个功能“从外部网站导入文章”。在我的第一个场景中,我测试从外部网站导入链接列表。Feature:ImportingarticlesfromexternalwebsiteScenario:Searchingarticlesonexample.comandreturnthelinksGiventhereisanImporterAnditsURLis"http://example.com"Whenwesearchfor"demo"ThentheImportershouldreturn25linksAndoneofthelinksshouldbe"http://example.com/d

随机推荐