In Flutter 3.x, ReorderableListView is not working - flutter

I'm trying to implement ReorderableListView in my Flutter app. The code is simple:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: MyHomePage()));
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void _onReorder(int oldIndex, int newIndex) => setState(
() => items.insert(
newIndex > oldIndex ? newIndex -= 1 : newIndex,
items.removeAt(oldIndex),
),
);
var items = ['Item A', 'Item B', 'Item C'];
#override
Widget build(context) => Scaffold(
body: ReorderableListView(
onReorder: _onReorder,
children: items.map((item) {
var index = items.indexOf(item);
return ListTile(
key: Key('$index'),
tileColor: Colors.white,
title: Text(item),
onTap: () {
// Handle tap
},
);
}).toList(),
),
);
}
I can't make the code work. The items can't be reordered. flutter --version command tells me:
Flutter 3.3.8 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 52b3dc25f6 (3 days ago) • 2022-11-09 12:09:26 +0800
Engine • revision 857bd6b74c
Tools • Dart 2.18.4 • DevTools 2.15.0
And flutter doctor tells me:
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.8, on macOS 13.0.1 22A400 darwin-x64, locale en-ID)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.3)
[✓] IntelliJ IDEA Ultimate Edition (version 2022.2.1)
[✓] VS Code (version 1.73.1)
[✓] Connected device (4 available)
[✓] HTTP Host Availability
• No issues found!
What is wrong with my code?

After many hours of trial and error with many samples and tutorials all over the internet, I have found the cause: In Flutter 3.x, ReorderableListView will only work if we use ReorderableDragStartListener. This is the 1 link that led me to the right direction: https://github.com/flutter/flutter/issues/114783. How to use the listener? I have to modify my code, and update the ListTile part as follows:
ListTile(
key: Key('$index'),
tileColor: Colors.white,
title: Text(item),
onTap: () {
// Handle tap
},
trailing: ReorderableDragStartListener(
index: index,
child: const Icon(Icons.drag_handle),
),
)
I hope this answer will help people, and no one gets through all the frustrating hours like I did.

Related

Error: A non-null value must be returned since the return type 'List<PigeonInitializeResponse?>' doesn't allow null

I need to run my project, and I'm getting the following error:
JUST PUT THE import:'package:firebase_auth/firebase_auth.dart'; IT GIVES ME THIS ERROR
C:/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_platform_interface-4.5.2/lib/src/pigeon/messages.pigeon.dart:198:43: Error: A non-null value must be returned since the return type 'List<PigeonInitializeResponse?>' doesn't allow null.
'List' is from 'dart:core'.
'PigeonInitializeResponse' is from 'package:firebase_core_platform_interface/src/pigeon/messages.pigeon.dart' ('/C:/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_platform_interface-4.5.2/lib/src/pigeon/messages.pigeon.dart').
package:firebase_core_platform_interface/…/pigeon/messages.pigeon.dart:1
Future<List<PigeonInitializeResponse?>> initializeCore() async {
Future<List<PigeonInitializeResponse?>> initializeCore() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as List<Object?>?)!
.cast<PigeonInitializeResponse>();
}
}
After the error appears in debug, it contains a link that leads to the error, the code is not mine.
I'm having a lot of trouble solving this error, because I'm a beginner in flutter and the code is not mine, it's inside the packages.
I've done flutter clean and flutter pub get.
I made sure the dependencies are all up to date.
I configured firebase, google-services in build.gradle, classpath, apply plugin and implementation.
flutter doctor -v:
[√] Flutter (Channel stable, 3.3.9, on Microsoft Windows [versÆo
10.0.19044.2251], locale pt-BR)
• Flutter version 3.3.9 on channel stable at C:\flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision b8f7f1f986 (6 days ago), 2022-11-23 06:43:51 +0900
• Engine revision 8f2221fbef
• Dart version 2.18.5
• DevTools version 2.15.0
[!] Android toolchain - develop for Android devices (Android SDK version
32.1.0-rc1)
• Android SDK at C:\Users\Rafael Pereira\AppData\Local\Android\sdk
X cmdline-tools component is missing
Run `path/to/sdkmanager --install "cmdline-tools;latest"`
See https://developer.android.com/studio/command-line for more details. X Android license status unknown.
Run `flutter doctor --android-licenses` to accept the SDK licenses.
See https://flutter.dev/docs/get-started/install/windows#android-setup
for more details.
[√] Chrome - develop for the web
• Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe
[X] Visual Studio - develop for Windows
X Visual Studio not installed; this is necessary for Windows development. Download at https://visualstudio.microsoft.com/downloads/.
Please install the "Desktop development with C++" workload, including
all of its default components
[!] Android Studio (version 2021.2)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
X Unable to find bundled Java version.
• Try updating or re-installing Android Studio.
[√] Android Studio (version 2021.3)
• Android Studio at C:\Program Files\Android\Android Studio1
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build
11.0.13+0-b1751.21-8125866)
[√] VS Code (version 1.73.1)
• VS Code at C:\Users\Rafael Pereira\AppData\Local\Programs\Microsoft VS
Code
• Flutter extension version 3.53.20221101
[√] Connected device (4 available)
• Android SDK built for x86 (mobile) • emulator-5554 • android-x86 •
Android 10 (API 29) (emulator)
• Windows (desktop) • windows • windows-x64 •
Microsoft Windows [versÆo 10.0.19044.2251]
• Chrome (web) • chrome • web-javascript •
Google Chrome 107.0.5304.121
• Edge (web) • edge • web-javascript •
Microsoft Edge 107.0.1418.56
[√] HTTP Host Availability
• All required HTTP hosts are available
! Doctor found issues in 3 categories.
My code - file main.dart:
import 'firebase_options.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart' show FirebaseAuth, User;
import 'package:pigeon/pigeon.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import './login_page.dart';
import './next_page.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const LoginPage(),
debugShowCheckedModeBanner: false,
);
}
}
class Mainpage extends StatelessWidget {
const Mainpage({super.key});
#override
Widget build(BuildContext context) => Scaffold(
body: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return const NextPage();
} else {
return const LoginPage();
}
},
),
);
}
My code login_page.dart:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
#override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final emailController = TextEditingController();
final passwordController = TextEditingController();
#override
void dispose() {
emailController.dispose();
passwordController.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(233, 30, 34, 88),
body: Center(
child: Container(
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Login",
style: TextStyle(fontSize: 40, color: Colors.white),
),
SizedBox(
height: 18,
),
Card(
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0)),
child: Container(
height: 200,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Color.fromARGB(108, 217, 220, 221)),
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(15),
child: TextField(
controller: emailController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(hintText: "E-mail"),
),
),
SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.all(15),
child: TextField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(hintText: "Password"),
),
),
],
),
),
),
SizedBox(
height: 20,
),
SizedBox(
height: 50,
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
style: TextButton.styleFrom(
backgroundColor: Colors.lightBlueAccent[700],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
),
child: Text(
'Logar',
style: TextStyle(fontSize: 18, color: Colors.white),
),
onPressed: signIn,
)),
SizedBox(
height: 15,
),
TextButton(
child: Text('Esqueceu sua senha?'),
onPressed: () {},
)
],
),
),
),
);
}
Future signIn() async {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailController.text.trim(),
password: passwordController.text.trim(),
);
}
}
I've appealed to some people, but nothing solved.
I tried simple things, but I'm a beginner and I end up being limited.
I made all the updates, and possible settings that could be interfering.
files pubspec.yaml:
Firebase
firebase_auth: ^4.1.4
firebase_messaging: ^14.1.2
firebase_database: ^10.0.6
firebase_core: ^2.3.0
firebase_core_platform_interface: ^4.5.2
Dart Pigeon
pigeon: ^4.2.6
Flutterfire
flutterfire_cli: ^0.2.7

Flutter semantic label does not work with VoiceOver on iOS

This is an app specifically for blind and partially sighted users and rely heavily on VoiceOver who mainly use the iPhone. Upgraded to Flutter 3.0.2 did a flutter clean, pub upgrade and pub get but the issue still persists. Running on an iPhone SE 2nd Gen with iOS 15.5
Any possible workaround would be much appreciated. Thanks.
Steps to Reproduce
Execute flutter run on the code sample
Enable VoiceOver on iOS
Tap on any or all of the 3 displayed icons "compose", "camera" & "chat"
Expected results:
Expected the VoiceOver to read out the semantic labels: edit profile, camera screen & chat screen
Actual results:
VoiceOver instead reads out: compose, camera button, chat button
Even tried it with the "Semantics" widget with a label and excluding the children but the same issue (This works perfectly on Android 11 (OnePlus Nord2 CE) though)
Code sample:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'VoiceOver Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'VoiceOver Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: InkWell(
onTap: () {},
child: IconButton(
icon: const Icon(Icons.edit, semanticLabel: "edit profile",),
tooltip: 'edit profile tooltip', onPressed: () { },
),
),
),
bottomNavigationBar: BottomAppBar(
color: Theme.of(context).colorScheme.secondary,
elevation: 5,
child: Row(
children: [
IconButton(
icon: Icon(
Icons.camera_alt_outlined,
size: 36,
color: _currentIndex == 0 ? Colors.white:Colors.grey,
semanticLabel: "camera screen",
),
onPressed: () {
_currentIndex = 0;
print("Page 1");
}
),
const Spacer(),
IconButton(
icon: Icon(
Icons.chat_outlined,
size: 36,
color: _currentIndex == 1 ? Colors.white:Colors.grey,
semanticLabel: "chat screen",
),
onPressed: () {
_currentIndex = 1;
print("Page 2");
}
),
],
),
),// This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Few others I tried:
body: Center(
child: Semantics(
label: "edit profile",
excludeSemantics: true,
child: IconButton(
icon: const Icon(
Icons.edit,
size: 36,
color: Colors.blue,
),
onPressed: () {
}
),
)),
body: Center(
child: Semantics(
onDidGainAccessibilityFocus: () {
SemanticsService.announce("edit profile", TextDirection.ltr);
},
label: "edit profile label",
excludeSemantics: true,
child: IconButton(
icon: const Icon(
Icons.edit,
size: 36,
color: Colors.blue,
),
onPressed: () {
}
),
)),
Logs:
/Users/me/Projects/voiceoverdemo/voiceoverdemo_test_flutter/ios/Runner/Info.plist
[ ] <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>VoiceOver Test Flutter</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>voiceoverdemo_test_flutter</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
{
"simulator" : false,
"operatingSystemVersion" : "15.5 (19F77)",
"interface" : "usb",
"available" : true,
"platform" : "com.apple.platform.iphoneos",
"modelCode" : "iPhone12,8",
"identifier" : "XXXXXXXX-XXXXXXXXXXXXXXXX",
"architecture" : "arm64e",
"modelUTI" : "com.apple.iphone-se-1",
"modelName" : "iPhone SE",
"name" : "Me's iPhone"
},
flutter analyze:
Analyzing voiceoverdemo_test_flutter...
No issues found! (ran in 2.5s)
flutter doctor -v
[✓] Flutter (Channel stable, 2.10.5, on macOS 12.3.1 21E258 darwin-x64, locale en-GB)
• Flutter version 2.10.5 at /Users/me/software/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 5464c5bac7 (8 weeks ago), 2022-04-18 09:55:37 -0700
• Engine revision 57d3bac3dd
• Dart version 2.16.2
• DevTools version 2.9.2
[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
• Android SDK at /Users/me/Library/Android/sdk
• Platform android-31, build-tools 31.0.0
• Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• CocoaPods version 1.11.2
[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Android Studio (version 2021.2)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
[✓] IntelliJ IDEA Community Edition (version 2021.3.3)
• IntelliJ at /Applications/IntelliJ IDEA CE.app
• Flutter plugin version 66.0.3
• Dart plugin version 213.7371
[✓] VS Code (version 1.68.0)
• VS Code at /Users/me/Software/Visual Studio Code.app/Contents
• Flutter extension version 3.42.0
[✓] Connected device (2 available)
• Me's iPhone (mobile) • XXXXXXXX-XXXXXXXXXXXXX • ios • iOS 15.5 19F77
• Chrome (web) • chrome • web-javascript • Google Chrome 102.0.5005.115
[✓] HTTP Host Availability
• All required HTTP hosts are available
• No issues found!
https://user-images.githubusercontent.com/5812030/174106131-a6be4e0c-e650-46cf-87ea-0c635c0d04c5.jpg
This works fine in the simulator with the Accessibility Inspector:
https://user-images.githubusercontent.com/5812030/174129522-29ff6a1f-38a4-4593-93c5-4f34e08e891e.png
Recording:
https://user-images.githubusercontent.com/5812030/174270320-159d3fb7-135a-417b-b9d1-c3a8e2f526f1.MP4
Found the issue. For some reason a setting was enabled on my iPhone. When I switched it off it worked perfectly.
Settings -> Accessibility -> Voice Over -> VoiceOver Recognition -> Screen Recognition -> Apply to Apps
This setting had the app added to it. When I removed the app from this list it worked fine

text not appear in release mode flutter andriod

I run my app in debug mode , it works fine but when generate apk the text not show, this some images in debug and release.
Debug Mode:
Release Mode:
[environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.0
flutter_localizations:
sdk: flutter
sizer: ^1.1.8
gradient_app_bar: ^0.1.3
http: ^0.13.4
rflutter_alert: ^1.1.0
loading_overlay: ^0.2.1
shared_preferences: ^2.0.13
anim_search_bar: ^1.0.1
geolocator: ^7.6.2
flutter_polyline_points: ^0.2.4
google_maps_flutter: ^2.1.1
maps_launcher: ^2.0.1
new_gradient_app_bar: ^0.1.5
multi_select_flutter: ^3.1.8
image_picker: ^0.8.4+8
printing: ^5.7.2
pdf: ^3.7.1
flutter_image_compress: ^1.1.0
connectivity_plus: ^2.2.1]
[✓] Flutter (Channel stable, 2.10.1, on Mac OS X 10.15.7 19H1713
darwin-x64, locale en-SA)
• Flutter version 2.10.1 at /Users/raitotec/developer/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision db747aa133 (4 weeks ago), 2022-02-09 13:57:35 -0600
• Engine revision ab46186b24
• Dart version 2.16.1
• DevTools version 2.9.2
[✓] Android toolchain - develop for Android devices (Android SDK
version 30.0.2)
• Android SDK at /Users/raitotec/Library/Android/sdk
• Platform android-31, build-tools 30.0.2
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
• All Android licenses accepted.
[!] Xcode - develop for iOS and macOS (Xcode 12.4)
• Xcode at /Applications/Xcode.app/Contents/Developer
! Flutter recommends a minimum Xcode version of 13.
Download the latest version or update via the Mac App Store.
• CocoaPods version 1.11.2
[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Android Studio (version 4.0)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 51.0.1
• Dart plugin version 193.7547
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
[✓] Connected device (2 available)
• iPhone 12 mini (mobile) • A9648508-3B05-4468-B593-477288FC7370 • ios • com.apple.CoreSimulator.SimRuntime.iOS-14-4
(simulator)
[✓] HTTP Host Availability
• All required HTTP hosts are available
this my page code
import 'dart:convert';
import 'package:delegate_app/Api/LoginApi.dart';
import 'package:delegate_app/Constans/Style.dart';
import 'package:delegate_app/Localization/language.dart';
import 'package:delegate_app/Localization/language_constants.dart';
import 'package:delegate_app/Routes/route_constants.dart';
import 'package:delegate_app/Shared_View/AppBarView.dart';
import 'package:delegate_app/main.dart';
import 'package:flutter/material.dart';
import 'package:loading_overlay/loading_overlay.dart';
import 'package:sizer/sizer.dart';
class startPage extends StatefulWidget {
startPage({Key key}) : super(key: key);
#override
_startPageState createState() => _startPageState();
}
class _startPageState extends State<startPage> {
final _formKey = GlobalKey<FormState>();
TextEditingController nameController = TextEditingController();
bool _isLoading = false;
#override
Widget build(BuildContext context) {
return SafeArea(child: Scaffold(
//resizeToAvoidBottomInset: false,
// appBar: AppBarWithBack(context, ''),
body: LoadingOverlay(
child: Container(
height: double.infinity,
width: double.infinity,
decoration: Style.BoxDecoration1,
child: FormUI(),
),
isLoading: _isLoading,
opacity: 0.2,
color: Style.MainColor,
progressIndicator: CircularProgressIndicator(valueColor: new AlwaysStoppedAnimation<Color>(Style.MainColor),))
));
}
Widget FormUI() {
return Center(child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(padding: EdgeInsets.symmetric( vertical: 15.0),),
// Image(image: AssetImage('lib/assets/logo.png'), width: 50.0.w),
Container(
decoration: Style.BoxDecorationWithRadiusOny,
margin: EdgeInsets.symmetric( horizontal: 35.0 ,vertical: 30.0),
child: Form(
key: _formKey,
child:Padding(
padding: EdgeInsets.symmetric( horizontal: 20.0, vertical: 20.0),
child:Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
//Password
Theme(
data: Theme.of(context).copyWith(primaryColor: Style.SecondryColor ),
child: TextFormField(
// obscureText: true,
controller: nameController,
validator: (value) {
if (value.isEmpty) {
return getTranslated(context,'CompanyNumber_Validation');
}
return null;
},
cursorColor: Style.SecondryColor,
style: Style.MainText14,
decoration: InputDecoration(
icon: Icon(Icons.home_work_outlined),
hintText: '',
labelText: getTranslated(context, 'CompanyNumber'),
labelStyle: Style.GreyText14,
hintStyle: Style.GreyText14,
errorStyle: Style.GreyText14.copyWith(color: Colors.red)
),
onEditingComplete: () {
FocusScope.of(context).unfocus();
}
),
),
// Login Button
Padding(
padding: EdgeInsets.fromLTRB(0, 2.0.h, 0, 0),
child: Container(
padding: EdgeInsets.fromLTRB(0, 1.0.h, 0, 1.0.h),
decoration: Style.BoxDecorationWithRadius,
child: FlatButton(
child: Text(
getTranslated(context, 'login_btn'),
style: Style.Header5,
),
onPressed: ()async {
if (_formKey.currentState.validate()) {
showLoading();
var res= await StartToLogin(context,nameController.text);
hideLoading();
if(res != null)
{
Navigator.pushNamed(context, loginRoute);
}
}},
),
),
),
],
),
),),
),
],
),
);
}
void showLoading() {
setState(() {
_isLoading=true;
});
}
void hideLoading() {
setState(() {
_isLoading=false;
});
}
}
this code of getTranslated
String getTranslated(BuildContext context, String key) {
return DemoLocalization.of(context).translate(key);
}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class DemoLocalization {
DemoLocalization(this.locale);
final Locale locale;
static DemoLocalization of(BuildContext context) {
return Localizations.of<DemoLocalization>(context, DemoLocalization);
}
Map<String, String> _localizedValues;
Future<void> load() async {
String jsonStringValues =
await rootBundle.loadString('lib/lang/${locale.languageCode}.json');
Map<String, dynamic> mappedJson = json.decode(jsonStringValues);
_localizedValues =
mappedJson.map((key, value) => MapEntry(key, value.toString()));
}
String translate(String key) {
return _localizedValues[key];
}
// static member to have simple access to the delegate from Material App
static const LocalizationsDelegate<DemoLocalization> delegate =
_DemoLocalizationsDelegate();
}
class _DemoLocalizationsDelegate
extends LocalizationsDelegate<DemoLocalization> {
const _DemoLocalizationsDelegate();
#override
bool isSupported(Locale locale) {
return ['en', 'ar',].contains(locale.languageCode);
}
#override
Future<DemoLocalization> load(Locale locale) async {
DemoLocalization localization = new DemoLocalization(locale);
await localization.load();
return localization;
}
#override
bool shouldReload(LocalizationsDelegate<DemoLocalization> old) => false;
}
Problem is from the package 'Sizer' it returns ZERO when you use .sp on Texts,
make sure that you have your Material app Wrapped directly with Sizer inside build function
Widget build(BuildContext context) {
return Sizer(builder: (context, orientation, deviceType) {
return MaterialApp(); });
}
if that doesn't work for you, you can override fontSize for Text widgets styles like:
Text(
getTranslated(context, 'login_btn'),
style: Style.Header5?.copyWith(fontSize: 14.sp),
)

Flutter Windows : TextField does not allow space if it is placed inside AlertDialog

One hour ago I discovered a TextField strange behavior when I place it inside AlertDialog it does not allow typing space Otherwise it behaves normally here is my code:
//================Flutter doctor -v
[√] Flutter (Channel stable, 2.0.2, on Microsoft Windows [Version 10.0.18363.1316], locale en-US)
• Flutter version 2.0.2 at C:\Flutter\flutter-latest
• Framework revision 8962f6dc68 (5 days ago), 2021-03-11 13:22:20 -0800
• Engine revision 5d8bf811b3
• Dart version 2.12.1
[√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
• Android SDK at C:\Users\user\AppData\Local\Android\sdk
• Platform android-30, build-tools 29.0.3
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)
• All Android licenses accepted.
[√] Chrome - develop for the web
• Chrome at C:\Users\user\AppData\Local\Google\Chrome\Application\chrome.exe
[√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.9.0)
• Visual Studio at C:\Program Files (x86)\Microsoft Visual Studio\2019\Community
• Visual Studio Community 2019 version 16.9.31025.194
• Windows 10 SDK version 10.0.19041.0
[√] Android Studio (version 3.5)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 42.1.1
• Dart plugin version 191.8593
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)
[√] IntelliJ IDEA Community Edition (version 2020.2)
• IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2.1
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
[√] VS Code (version 1.54.3)
• VS Code at C:\Users\user\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.20.0
[√] Connected device (3 available)
• Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.18363.1316]
• Chrome (web) • chrome • web-javascript • Google Chrome 89.0.4389.82
• Edge (web) • edge • web-javascript • Microsoft Edge 89.0.774.54
• No issues found!
//======AppTextField widget
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class AppTextField extends StatefulWidget {
final String caption;
final dynamic initialValue;
final dynamic Function(String) onSubmitted;
final bool readOnly;
const AppTextField(
{Key key,
this.caption,
this.onSubmitted,
this.initialValue,
this.readOnly = false})
: super(key: key);
#override
_AppTextFieldState createState() => _AppTextFieldState();
}
class _AppTextFieldState extends State<AppTextField> {
TextEditingController _textEditingController;
TextStyle _captionStyle = TextStyle(fontSize: 17);
TextStyle _textStyle = TextStyle(fontSize: 17);
String get value => _textEditingController.text;
#override
void initState() {
super.initState();
this._textEditingController = TextEditingController();
this._textEditingController.text = this.widget.initialValue != null
? this.widget.initialValue.toString()
: "";
}
#override
Widget build(BuildContext context) {
return TextField(
textInputAction: TextInputAction.none,
readOnly: this.widget.readOnly,
enableInteractiveSelection: true,
cursorHeight: 30,
onEditingComplete: () {
int u = 9;
},
onChanged: (v) {
// if (this.widget.onSubmitted != null) {
// var val = this.widget.onSubmitted(v);
// if (val != null) this._textEditingController.text = val.toString();
// }
},
style: _textStyle,
controller: _textEditingController,
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.all(15.0),
labelText: this.widget.caption,
floatingLabelBehavior: FloatingLabelBehavior.always,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(color: Colors.green, width: 1.0))),
);
}
#override
void dispose() {
this._textEditingController.dispose();
super.dispose();
}
}
//======the I use AppTextField widget inside AlertDialog like this :
import 'package:animate_do/animate_do.dart';
import 'package:flutter/material.dart';
import 'package:flutter_desktop/Views/App-Widgets/AppTextField.dart';
import 'package:flutter_desktop/Views/Room/Notification-Dialog.dart';
import 'package:flutter_desktop/Views/states/Message-State.dart';
import 'package:provider/provider.dart';
import 'Chat/ChatMessage.dart';
class SendNotificationDialog extends StatefulWidget {
#override
_SendNotificationDialogState createState() => _SendNotificationDialogState();
}
class _SendNotificationDialogState extends State<SendNotificationDialog> {
String _message = "";
#override
Widget build(BuildContext context) {
return AlertDialog(
elevation: 10,
titleTextStyle: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold, color: Colors.black),
title: Text("رسالة تنبيه"),
content: Builder(
builder: (context) => _createBody(context),
),
actions: [
MaterialButton(
onPressed: () {
Navigator.pop(context);
var messageState =
Provider.of<MessageState>(context, listen: false);
messageState.addMessage(_message, MessageType.NOTIFICATION);
Navigator.push(
context,
PageRouteBuilder(
barrierDismissible: true,
opaque: false,
pageBuilder: (_, __, ___) => NotificationDialog(
userName: "Yousel : ",
notification: _message,
)));
},
child: Text("موافق"),
),
MaterialButton(
onPressed: () {
Navigator.pop(context);
},
child: Text("إلغاء"),
),
],
);
}
_createBody(BuildContext context) {
return Container(
width: 500,
height: 100,
child: ListTile(
autofocus: true,
title: AppTextField(
initialValue: _message,
onSubmitted: (v) {
_message = v;
return _message;
},
caption: "أدخل النص الذى سوف يشاهده الجميع",
),
),
);
}
}
//=======Then I push SendNotificationDialog page :
Navigator.push(
context,
PageRouteBuilder(
barrierDismissible: true,
opaque: false,
transitionDuration: Duration(milliseconds: 500),
transitionsBuilder:
(context, firstAnimation, secondAnimation, child) {
firstAnimation = CurvedAnimation(
parent: firstAnimation, curve: Curves.fastLinearToSlowEaseIn);
return ScaleTransition(
scale: firstAnimation,
child: child,
);
},
pageBuilder: (_, __, ___) {
return SendNotificationDialog();
}));
The problem was caused by wrapping the TextField inside a ListTile widget, not by wrapping that in an AlertDialog. Removing the ListTile solves the problem.

flutter DropDownButtonFormField hint throws runtime error

I am getting this error on runtime when using DropdownButtonFormField:
════════ Exception caught by widgets library ═══════════════════════════════════
The following _TypeError was thrown building DropdownButton<int>(dirty, dependencies: [_InheritedTheme, Directionality, DropdownButtonHideUnderline, MediaQuery, _LocalizationsScope-[GlobalKey#c5725]], state: _DropdownButtonState<int>#eb5d0):
type 'DefaultTextStyle' is not a subtype of type 'Row' of 'value'
The relevant error-causing widget was
DropdownButtonFormField<int>
this is a sample of my code:
int _selectedSchoolId;
DropdownButtonFormField<int> _schlDropdown(List<School> _schools) {
return DropdownButtonFormField(
value: _selectedSchoolId,
decoration: SMTextField.getDecoration(
context,
hintColor: Colors.white,
),
hint: Text(InAppMethods.getStr('select_school')),
selectedItemBuilder: (context) =>
_schools.map((e) => _school(e, true)).toList(),
items: _schools.map((e) {
final String _name = Statics.isRTL() ? e.nameAr : e.nameEn;
final double _wdt = 30;
final bool _img = e?.image != null;
return DropdownMenuItem<int>(
child: Center(
child: Row(
children: [
if (_img)
Image.network(
e?.image,
width: _wdt,
height: _wdt,
),
SizedBox(
width: _img ? _wdt : _wdt * 2,
),
Text(
_name ?? '',
style: TextStyle(color: Colors.black),
),
],
),
),
value: e.id,
);
}).toList(),
onChanged: (id) => setState(() => _selectedSchoolId = id),
);
}
and this is my flutter doctor -v output:
[✓] Flutter (Channel stable, 1.22.5, on Mac OS X 10.15.7 19H2 darwin-x64, locale en-TR)
• Flutter version 1.22.5 at /Users/adnanfahed/flutter
• Framework revision 7891006299 (3 days ago), 2020-12-10 11:54:40 -0800
• Engine revision ae90085a84
• Dart version 2.10.4
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
• Android SDK at /Users/adnanfahed/Library/Android/sdk
• Platform android-30, build-tools 30.0.2
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 12.2, Build version 12B45b
• CocoaPods version 1.10.0
[✓] Android Studio (version 4.1)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin installed
• Dart plugin version 201.9245
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
[✓] VS Code (version 1.52.0)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.17.0
[✓] Connected device (1 available)
• sdk gphone x86 arm (mobile) • emulator-5554 • android-x86 • Android 11 (API 30) (emulator)
• No issues found!
Try this one:
int _selectedSchoolId;
DropdownButtonFormField<int> _schlDropdown(List<School> _schools) {
return DropdownButtonFormField(
value: _selectedSchoolId,
hint: Text(
InAppMethods.getStr('select_school',
style: TextStyle(color: Colors.white,)),
selectedItemBuilder: (context) =>
_schools.map((e) => _school(e, true)).toList(),
items: _schools.map((e) {
final String _name = Statics.isRTL() ? e.nameAr : e.nameEn;
final double _wdt = 30;
final bool _img = e?.image != null;
return DropdownMenuItem<int>(
child: Center(
child: Row(
children: [
if (_img)
Image.network(
e?.image,
width: _wdt,
height: _wdt,
),
SizedBox(
width: _img ? _wdt : _wdt * 2,
),
Text(
_name ?? '',
style: TextStyle(color: Colors.black),
),
],
),
),
value: e.id,
);
}).toList(),
onChanged: (id) => setState(() => _selectedSchoolId = id),
);
}