flutter TextFormField 在生产模式下宽度为零。

huangapple go评论46阅读模式
英文:

flutter TextFormField width is zero in production mode

问题

I write a dictionary app and I have a TextFormField on the main page it shows well on my mobile and emulator. when run on other devices the TextFormField width is zero or disappeared.

if you guys are faced with this kind of problem share your experience

What I expect:

<img src="https://i.stack.imgur.com/gi4Ib.jpg" width="300">

What I faced:

<img src="https://i.stack.imgur.com/i8SkB.png" width="300">

home page code:

import 'dart:math';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:sundic/app/modules/home/mylabel.dart';
import 'package:sundic/app/routes/app_pages.dart';
import 'package:sundic/generated/locales.g.dart';
import '../controllers/home_controller.dart';

class HomeView extends GetView<HomeController> {
  const HomeView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => await _showRatingDialog(context),
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          forceMaterialTransparency: true,
          toolbarHeight: Get.width * .30,
          title: Obx(
            () => controller.isLoaded.value
                ? SizedBox(
                    width: controller.bannerAd!.size.width.toDouble(),
                    height: controller.bannerAd!.size.height.toDouble(),
                    child: AdWidget(ad: controller.bannerAd!),
                  )
                : const SizedBox.shrink(),
          ),
          titleSpacing: 0,
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(5.0),
            child:

                // Obx(() => searchInput()),

                SizedBox(
              width: Get.size.width,
              height: 50,
              child: Obx(
                () => searchInput(),
              ),
            ),
          ),
        ),
        backgroundColor: Colors.grey.shade100,
        body: Stack(
          children: [
            // WordCloud(texts: controller.mylabels, focusedWord: controller.focusedWord),
            Obx(
              () => Container(
                height: Get.size.height,
                width: Get.size.width,
                margin: const EdgeInsets.only(top: 10),
                child: Container(
                  clipBehavior: Clip.antiAlias,
                  margin: const EdgeInsets.symmetric(horizontal: 15),
                  decoration: BoxDecoration(
                    color: controller.words.isNotEmpty ? Colors.white : Colors.transparent,
                    // borderRadius: const BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20)),
                  ),
                  child: ListView.separated(
                    physics: const BouncingScrollPhysics(),
                    padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 0),
                    itemCount: controller.words.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        onTap: () {
                          FocusScope.of(context).unfocus();
                          Get.toNamed(Routes.DETAILS, arguments: controller.words[index]);
                        },
                        contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                        title: Text(
                          controller.words[index].word ?? '',
                          textDirection: controller.words[index].wordDirection,
                        ),
                        subtitle: Directionality(
                          textDirection: controller.words[index].meaningDirection,
                          child: Text(
                            controller.words[index].meaning ?? '',
                            style: TextStyle(color: Colors.grey.shade700),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      );
                    },
                    separatorBuilder: (BuildContext context, int index) => const Divider(thickness: 0.5),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget searchInput() {
    return Container(
      width: Get.size.width,
      height: 50,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: IntrinsicWidth(
        stepHeight: Get.size.width,
        child: Container(
          width: double.infinity,
          height: double.infinity,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(0),
            border: Border.all(color: Colors.grey.shade300),
          ),
          child: TextFormField(
            autofocus: true,
            controller: controller.searchController,
            onTap: () => controller.moved.value = true,
            onChanged: (value) => controller.search(value),
            decoration: InputDecoration(
              hintText: LocaleKeys.search_placeholder.tr,
              border: InputBorder.none,
              suffixIcon: IconButton(
                onPressed: () => Get.toNamed(Routes.BOOKMARKED),
                icon: const Icon(Icons.star),
              ),
              prefixIcon: controller.hiddenButton.value
                  ? const Icon(Icons.search)
                  : IconButton(
                      onPressed: () {
                        controller.hiddenButton.value = true;
                        controller.searchController.clear();
                        controller.words.clear();
                      },
                      icon: const Icon(Icons.close)),
            ),
          ),
        ),
      ),
    );
  }

  Future<bool> _onWillPop() async {
    DateTime now = DateTime.now();
    if (controller.currentBackPressTime == null || now.difference(controller.currentBackPressTime!) > const Duration(seconds: 2)) {
      controller.currentBackPressTime = now;
      ScaffoldMessenger.of(Get.context!).showSnackBar(SnackBar(content: Text(LocaleKeys.press_back_again.tr), duration: const Duration(seconds: 2)));
      controller.reviewApp();
      return Future.value(false);
    }
    return Future.value(true);
  }

  Future<bool> _showRatingDialog(BuildContext context) async {
    bool shouldExit = false;
    await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(LocaleKeys.rate_the_app.tr),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(LocaleKeys.rate_the_app_description.tr),
            const SizedBox(height: 8),
          ],
        ),
        actionsAlignment: MainAxisAlignment.spaceEvenly,
        actions: [
          ElevatedButton(
            onPressed: () {
              shouldExit = true;
              Navigator.of(context).pop();
              controller.reviewApp();
            },
            child: Text(LocaleKeys.exit.tr),
          ),
          ElevatedButton(
            onPressed: () {
              shouldExit = false;
              Navigator.of(context).pop();
              // You can navigate the user to the Play Store/App Store for rating here
            },
            child: Text(LocaleKeys.rate.tr),
          ),
        ],
      ),
    );

    return shouldExit;
  }
}
英文:

I write a dictionary app and I have a TextFormField on the main page it shows well on my mobile and emulator. when run on other devices the TextFormField width is zero or disappeared.

if you guys are faced with this kind of problem share your experience

What I expect:

<img src="https://i.stack.imgur.com/gi4Ib.jpg" width="300">

What I faced:

<img src="https://i.stack.imgur.com/i8SkB.png" width="300">

home page code:

import &#39;dart:math&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;package:get/get.dart&#39;;
import &#39;package:google_mobile_ads/google_mobile_ads.dart&#39;;
import &#39;package:sundic/app/modules/home/mylabel.dart&#39;;
import &#39;package:sundic/app/routes/app_pages.dart&#39;;
import &#39;package:sundic/generated/locales.g.dart&#39;;
import &#39;../controllers/home_controller.dart&#39;;
class HomeView extends GetView&lt;HomeController&gt; {
const HomeView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async =&gt; await _showRatingDialog(context),
child: Scaffold(
appBar: AppBar(
centerTitle: true,
forceMaterialTransparency: true,
toolbarHeight: Get.width * .30,
title: Obx(
() =&gt; controller.isLoaded.value
? SizedBox(
width: controller.bannerAd!.size.width.toDouble(),
height: controller.bannerAd!.size.height.toDouble(),
child: AdWidget(ad: controller.bannerAd!),
)
: const SizedBox.shrink(),
),
titleSpacing: 0,
bottom: PreferredSize(
preferredSize: const Size.fromHeight(5.0),
child:
// Obx(() =&gt; searchInput()),
SizedBox(
width: Get.size.width,
height: 50,
child: Obx(
() =&gt; searchInput(),
),
),
),
),
backgroundColor: Colors.grey.shade100,
body: Stack(
children: [
// WordCloud(texts: controller.mylabels, focusedWord: controller.focusedWord),
Obx(
() =&gt; Container(
height: Get.size.height,
width: Get.size.width,
margin: const EdgeInsets.only(top: 10),
child: Container(
clipBehavior: Clip.antiAlias,
margin: const EdgeInsets.symmetric(horizontal: 15),
decoration: BoxDecoration(
color: controller.words.isNotEmpty ? Colors.white : Colors.transparent,
// borderRadius: const BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20)),
),
child: ListView.separated(
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 0),
itemCount: controller.words.length,
itemBuilder: (context, index) {
return ListTile(
onTap: () {
FocusScope.of(context).unfocus();
Get.toNamed(Routes.DETAILS, arguments: controller.words[index]);
},
contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
title: Text(
controller.words[index].word ?? &#39;&#39;,
textDirection: controller.words[index].wordDirection,
),
subtitle: Directionality(
textDirection: controller.words[index].meaningDirection,
child: Text(
controller.words[index].meaning ?? &#39;&#39;,
style: TextStyle(color: Colors.grey.shade700),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
);
},
separatorBuilder: (BuildContext context, int index) =&gt; const Divider(thickness: 0.5),
),
),
),
),
],
),
),
);
}
Widget searchInput() {
return Container(
width: Get.size.width,
height: 50,
padding: const EdgeInsets.symmetric(horizontal: 15),
child: IntrinsicWidth(
stepHeight: Get.size.width,
child: Container(
width: double.infinity,
height: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(0),
border: Border.all(color: Colors.grey.shade300),
),
child: TextFormField(
autofocus: true,
controller: controller.searchController,
onTap: () =&gt; controller.moved.value = true,
onChanged: (value) =&gt; controller.search(value),
decoration: InputDecoration(
hintText: LocaleKeys.search_placeholder.tr,
border: InputBorder.none,
suffixIcon: IconButton(
onPressed: () =&gt; Get.toNamed(Routes.BOOKMARKED),
icon: const Icon(Icons.star),
),
prefixIcon: controller.hiddenButton.value
? const Icon(Icons.search)
: IconButton(
onPressed: () {
controller.hiddenButton.value = true;
controller.searchController.clear();
controller.words.clear();
},
icon: const Icon(Icons.close)),
),
),
),
),
);
}
Future&lt;bool&gt; _onWillPop() async {
DateTime now = DateTime.now();
if (controller.currentBackPressTime == null || now.difference(controller.currentBackPressTime!) &gt; const Duration(seconds: 2)) {
controller.currentBackPressTime = now;
ScaffoldMessenger.of(Get.context!).showSnackBar(SnackBar(content: Text(LocaleKeys.press_back_again.tr), duration: const Duration(seconds: 2)));
controller.reviewApp();
return Future.value(false);
}
return Future.value(true);
}
Future&lt;bool&gt; _showRatingDialog(BuildContext context) async {
bool shouldExit = false;
await showDialog(
context: context,
builder: (context) =&gt; AlertDialog(
title: Text(LocaleKeys.rate_the_app.tr),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(LocaleKeys.rate_the_app_description.tr),
const SizedBox(height: 8),
],
),
actionsAlignment: MainAxisAlignment.spaceEvenly,
actions: [
ElevatedButton(
onPressed: () {
shouldExit = true;
Navigator.of(context).pop();
controller.reviewApp();
},
child: Text(LocaleKeys.exit.tr),
),
ElevatedButton(
onPressed: () {
shouldExit = false;
Navigator.of(context).pop();
// You can navigate the user to the Play Store/App Store for rating here
},
child: Text(LocaleKeys.rate.tr),
),
],
),
);
return shouldExit;
}
}

答案1

得分: 1

硬编码的宽度和填充值可能无法适应不同的屏幕尺寸。

  • 尝试移除IntrinsicWidth,因为它可能是不必要的,可能会引起这个问题。
  • 尝试移除borderRadius属性,因为它也可能会在不同的屏幕尺寸上引起问题。
  • 将填充值从const EdgeInsets.symmetric(horizontal: 15)修改为EdgeInsets.all(),以实现均匀的填充。

希望这能解决你的问题。

英文:

The hardcoded values for the width and padding might not be adapting to the different screen sizes .

  • Try removing the IntristicWidth as it might be unnecessary and
    could cause this problem .
  • Try Removing the borderRadius property as it can also cause problem on different screen sizes.
  • Modify the padding from const EdgeInsets.symmetric(horizontal: 15) to EdgeInsets.all() to give equal padding to all.

Hope this works and your issue is resolved

答案2

得分: 0

我找到了问题。我在使用getx包进行状态管理,我使用Get.width获取设备宽度,我认为这个包有时候会有bug,导致它不能正常工作并且返回宽度为零。

最终,我将Get.width替换为MediaQuery.of(context).size.width,它正常工作了。

英文:

I have found the problem. I'm using getx package for state management and I got the device width using Get.width and i think this package has bugs sometime it not working and gives me the zero for width.

finally, I replaced Get.width to MediaQuery.of(context).size.width and it work fine

huangapple
  • 本文由 发表于 2023年7月27日 23:29:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76781312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定