【问题标题】:Release build not shows some widgets in flutter, but debug build shows it in flutter发布版本不会在颤动中显示一些小部件,但调试版本会在颤动中显示它
【发布时间】:2022-07-01 06:47:14
【问题描述】:

This is debug mode

This is release mode

main.dart


import 'package:flutter/material.dart';
import 'package:no_balance/notification_api.dart';


import 'timer.dart';
import 'list.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  NotificationService().initNotification();
  runApp(const MainPage());
}

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

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


class _MainPageState extends State<MainPage> {

  @override
  Widget build(BuildContext context) =>
      DefaultTabController(
          length: 2,
          child: MaterialApp(
              debugShowCheckedModeBanner: false,
              home: Scaffold(
                appBar: AppBar(
                  backgroundColor: Colors.red,
                  title: const Text("No balance: only work"),
                  centerTitle: true,
                  bottom: const TabBar(
                    indicatorColor: Colors.white,
                    tabs: [
                      Tab(text: "TIME"),
                      Tab(text: "LIST")
                    ],
                  ),
                ),
                body: const TabBarView(
                  children: [
                    TimerPage(),
                    ListPage()
                  ],
                ),
              )
          )
      );
}

timer.dart

import 'package:flutter/material.dart';
import 'package:percent_indicator/percent_indicator.dart';
import 'notification_api.dart';
import 'dart:async';

import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;

class TimerPage extends StatefulWidget{
  const TimerPage({Key? key}) : super(key: key);
  @override
  _TimerPageState createState() => _TimerPageState();
}

class _TimerPageState extends State<TimerPage>
{

  @override
  void initState(){
    tz.initializeTimeZones();
    super.initState();
  }

  bool isPaused = true;
  int value = 1;
  static int TimeInSecond = 5;
  int MainTime = 5;
  double percent = 0.0;
  int h = 0, m = 0, s = 5;

  void UpdateTimeFunc() {
    List <String> arr = (timeInputTimeController.text).split(" ");
    if (arr.length == 3) {
      h = int.parse(arr[0]);
      m = int.parse(arr[1]);
      s = int.parse(arr[2]);
      if (arr.length == 3 && h >= 0 && m >= 0 && m < 60 && s >= 0 && s < 60){
        TimeInSecond = h * 3600 + m * 60 + s;
        MainTime = TimeInSecond;
        percent = 0;
        setState(() {
          h = TimeInSecond ~/ 3600;
          m = (TimeInSecond - h * 3600) ~/ 60;
          s = TimeInSecond % 60;
          ++value;
          isPaused = true;
        });
      }
      else {
        NotificationService().showNotification(id: 1, title: "ERROR", body: "Wrong time entry");
      }
    }
    else {
      NotificationService().showNotification(id: 1, title: "ERROR", body: "Wrong time entry");
    }
  }

  void _startCountDown() {
    Timer.periodic(const Duration(seconds: 1), (timer) {
      if (TimeInSecond > 0 && isPaused == false){
        setState((){
          if (TimeInSecond == 2){
            NotificationService().showNotification(id: 0, title: "TIME!!!", body: "Time is left");
          }
          TimeInSecond--;
          h = TimeInSecond ~/ 3600;
          m = (TimeInSecond - h * 3600) ~/ 60;
          s = TimeInSecond % 60;
        });
      }
      else{
        timer.cancel();
      }
    });
  }


  // Timer handler functions: play, pause, stop
  void PlayFunc(){
    if (isPaused == true && TimeInSecond != 0){
      isPaused = false;
      _startCountDown();
    }
  }

  void PauseFunc(){
    setState((){
      isPaused = true;
    });
  }

  void StopFunc(){
    setState((){
      isPaused = true;
      TimeInSecond = 0;
      h = 0; m = 0; s = 0;
    });
  }



  TextEditingController timeInputTimeController = TextEditingController();

  @override
  Widget build (BuildContext context)
  {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Stack(
          children: [
            Container(
              alignment: Alignment.topCenter,
              child: Column(
                children: [
                  const SizedBox(
                    width: 50,
                    height: 50,
                  ),
                  CircularPercentIndicator(
                    circularStrokeCap: CircularStrokeCap.round,
                    percent: TimeInSecond/MainTime,
                    animation: true,
                    animateFromLastPercent: true,
                    radius: 140.0,
                    lineWidth: 20.0,
                    progressColor: Colors.red,
                    center: Text(
                        TimeInSecond == 0 ? 'Time is left' : "$h:$m:$s",
                        textAlign: TextAlign.center,
                        style: const TextStyle(
                            color: Colors.red,
                            fontSize: 60.0
                        )
                    ),
                  ),
                ],
              )
            ),
            Container(
              alignment: Alignment.bottomCenter,
              margin: const EdgeInsets.all(70),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(
                    width: 60,
                    height: 60,
                    child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          primary: Colors.red,
                          shape: RoundedRectangleBorder( //to set border radius to button
                              borderRadius: BorderRadius.circular(30)
                          ),
                        ),
                        onPressed: PlayFunc,
                        child: const Icon(Icons.play_arrow)
                    ),
                  ),
                  const SizedBox(
                    width: 20,
                  ),
                  SizedBox(
                    width: 60,
                    height: 60,
                    child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          primary: Colors.red,
                          shape: RoundedRectangleBorder( //to set border radius to button
                              borderRadius: BorderRadius.circular(30)
                          ),
                        ),
                        onPressed: PauseFunc,
                        child: const Icon(Icons.pause)
                    ),
                  ),
                  const SizedBox(
                    width: 20,
                  ),
                  SizedBox(
                    width: 60,
                    height: 60,
                    child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          primary: Colors.red,
                          shape: RoundedRectangleBorder( //to set border radius to button
                              borderRadius: BorderRadius.circular(30)
                          ),
                        ),
                        onPressed: StopFunc,
                        child: const Icon(Icons.stop)
                    ),
                  )
                ],
              ),
            ),
            Container(
              alignment: Alignment.bottomCenter,
              margin: const EdgeInsets.all(5),
              child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Expanded(
                    child: TextField(
                      controller: timeInputTimeController,
                      decoration: InputDecoration(
                        border: UnderlineInputBorder(
                          borderRadius: BorderRadius.circular(30.0),
                        ),
                        hintText: "Type by 'Space': 0 54 5 is 0:54:05",
                        fillColor: Colors.grey[200],
                        filled: true,
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 5,
                  ),
                  SizedBox(
                    width: 50,
                    height: 50,
                    child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          primary: Colors.red,
                          shape: RoundedRectangleBorder( //to set border radius to button
                              borderRadius: BorderRadius.circular(30)
                          ),
                        ),
                        onPressed: () => {UpdateTimeFunc()},
                        child: const Icon(Icons.send)
                    ),
                  )
                ],
              ),
            )
          ],
        )
      ),
    );
  }
}

list.dart

// library no_balance.list;

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

List<String> tasks = [];

class ListPage extends StatefulWidget {
  const ListPage({Key? key}) : super(key: key);
  @override
  _ListPageState createState() => _ListPageState();
}


class _ListPageState extends State<ListPage>
{

  int value = 1;
  TextEditingController taskInputController = TextEditingController();


  Future<void> _getList () async
  {
    final prefs = await SharedPreferences.getInstance();
    final tasks = prefs.getStringList('tasks');
    setState(() {
      ++value;
    });
  }

  void UpdateData() async {
    if (taskInputController.text != "") {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      tasks.add(taskInputController.text);
      await prefs.remove('tasks');
      await prefs.setStringList('tasks', tasks);
      setState(() {
        ++value;
      });
    }
  }

  void RemoveElementFromStorage(int index) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    tasks.removeAt(index);
    final success = await prefs.remove('tasks');
    await prefs.setStringList('tasks', tasks);
  }

  @override
  void initState() {
    super.initState();
    // _getList();
    SharedPreferences.getInstance().then((SharedPreferences sp) {
      var sharedPreferences = sp;
      tasks = sp.getStringList('tasks')!;
      setState(() {++value;});
    });
  }

  @override
  Widget build (BuildContext context)
  {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        resizeToAvoidBottomInset: false,
        body:Stack(
          children: <Widget>[
            ListView.builder(
              padding: const EdgeInsets.all(0),
              itemCount: tasks.length,
              itemBuilder: (context, index)
              {
                return ListTile(
                    title: Text(tasks[index]),
                    trailing: const Icon(Icons.restore_from_trash_rounded, size: 30,),
                  onTap: () {
                    setState(() {
                      // tasks.removeAt(index);
                      RemoveElementFromStorage(index);
                    });
                  }
                );
              },
            ),

            Container(
              alignment: Alignment.bottomCenter,
              margin: const EdgeInsets.all(5),
              child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Expanded(
                    child: TextField(
                        controller: taskInputController,
                        decoration: InputDecoration(
                          border: UnderlineInputBorder(
                            borderRadius: BorderRadius.circular(30.0),
                          ),
                          hintText: "Enter your task",
                          fillColor: Colors.grey[200],
                          filled: true,
                        ),
                    ),
                  ),
                  const SizedBox(
                    width: 5,
                  ),
                  SizedBox(
                    width: 50,
                    height: 50,
                    child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          primary: Colors.red,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(30)
                          ),
                        ),
                        onPressed: () => {UpdateData()},
                        child: const Icon(Icons.send)
                    ),
                  )
                ],
              ),
            )
          ],
        )
      )
    );
  }
}

我使用 flutter build apk --debugflutter build apk --release 进行了构建。

程序有另一个权限:

android:showWhenLocked="true"

android:turnScreenOn="true"

在 android 6 上使用手机进行测试。 Flutter 和所有包更新到最新版本。 控制台不输出任何错误。

Dev tools screen

我该如何解决?

【问题讨论】:

  • 请分享您的代码或提供更多信息。用这么少的信息很难理解你的问题。
  • 在执行过程中,flutter 引发了一些错误。这些可以在运行选项卡下(最底部)或通过 Flutter DevTools 找到。请尝试修复它,或分享您的代码的 sn-p,以便我们也可以尝试帮助您
  • @SamGarg 我添加了代码
  • @Delwinn 我添加了代码
  • 请检查flutter devtools日志; youtube.com/watch?v=b4dCHbINmyk&t=200s

标签: flutter dart mode


【解决方案1】:

它是否在控制台中显示“不正确使用父数据小部件”?如果是,您将错误的小部件包装在树内。假设您正在使用任何扩展或灵活尝试将其放在行或列内。

【讨论】:

  • 控制台没有错误
  • 我添加了代码
  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

我遇到了和你一样的问题,我终于解决了。问题似乎是小部件未正确初始化,因此当您在 main() 函数中运行应用程序时,您必须等待或延迟

也许这会有所帮助:

而不是这个:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  NotificationService().initNotification();
  runApp(const MainPage());
}

你可以拥有:

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  NotificationService().initNotification();
  await Future.delayed(const Duration(milliseconds: 300));
  runApp(const MainPage());
}

我的回答是指这个回答:https://stackoverflow.com/a/71614185/15188468

希望这会有所帮助

【讨论】:

    猜你喜欢
    • 2017-11-26
    • 2019-03-19
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2021-07-13
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多