why the SmartRefresher does not work in flutter - flutter

Now I am using SmartRefresher to refresh my app when pull down article list, I add pull_to_refresh dependencies in pubspec.yaml like this:
pull_to_refresh: 1.6.3
and this is my code:
child: CupertinoScrollbar(
child: SmartRefresher(
onRefresh: _onRefresh,
enablePullUp: true,
enablePullDown: true,
header: WaterDropMaterialHeader(),
controller: _refreshController,
onLoading: _loadingMoreArticle,
footer: CustomFooter(
builder: (BuildContext context, LoadStatus mode) {
Widget body;
if (mode == LoadStatus.idle) {
body = Text("上拉加载更多");
} else if (mode == LoadStatus.loading) {
body = CupertinoActivityIndicator();
} else if (mode == LoadStatus.failed) {
body = Text("加载失败!点击重试!");
} else if (mode == LoadStatus.canLoading) {
body = Text("release to load more");
} else {
body = Text("No more Data");
}
return Container(
height: 55.0,
child: Center(child: body),
);
},
),
child: CupertinoScrollbar(
child: CustomScrollView(
controller: scrollController,
slivers: <Widget>[
SliverOverlapInjector(
handle: NestedScrollView.sliverOverlapAbsorberHandleFor(
context,
),
),
if (state.articleListState.articleIds != null && state.articleListState.articleIds.length > 0)
SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
sliver: viewService.buildComponent("articlelist"),
)
],
)))));
but the UI does not contain any effect of SmartRefresher, the header shows nothing when pull, and the footer shows nothing when push up, am I missing something? what should I do to fix it? Now I am using macOS Catalina 10.15.7 and Android Studio 4.1.2.
$ dart --version
Dart SDK version: 2.10.2 (stable) (Tue Oct 13 15:50:27 2020 +0200) on "macos_x64"
(base)
$ ~/apps/flutter/bin/flutter --version
Flutter 1.22.5 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 7891006299 (7 weeks ago) • 2020-12-10 11:54:40 -0800
Engine • revision ae90085a84
Tools • Dart 2.10.4
(base)
this is the header shows when pull down:

The SmartRefresher needs to be higher up the widget tree than other scrolling widgets which will conflict/override the pull up/pull down action for the refresher. You can wrap your entire widget tree in a container(full width and height of the screen) and apply the SmartRefresher to that with everything else a child, or test out moving the refresher further up the widget tree.

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 Web FilePicker browser crash or close without error on UBUNTU

I want to use flutter file picker on web platform. when i call method "pickFiles" app close without error
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
);
print(result?.files.first.bytes);
if (result?.files.first != null) {
print(result?.files.first.bytes);
} else {
throw "Cancelled File Picker";
}
I think this is happening only on ubuntu.
and flutter doctor:
[✓] Flutter (Channel stable, 3.0.1, on Ubuntu 20.04.3 LTS 5.13.0-44-generic, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0-rc2)
[✓] Chrome - develop for the web
[✓] Linux toolchain - develop for Linux desktop
[✓] Android Studio (version 4.1)
[✓] VS Code
[✓] Connected device (2 available)
[✓] HTTP Host Availability
I have the same problem !
Temporarly i decide to use another package
flutter_dropzone: ^3.0.5
He helps me to put some files in the app.
onTap: () async {
bool fileUploaded = false;
double pourcentageUploaded = 0;
await showDialog(
context: context,
builder: (context) => Dialog(
child: StatefulBuilder(
builder: (context, setstate) => AnimatedContainer(
duration: Duration(seconds: 2),
color: fileUploaded
? Colors.green
: Colors.transparent,
height: 200,
width: 500,
child: Stack(
children: [
DropzoneView(
onDrop: (value) async {
fileUploaded = !fileUploaded;
do {
pourcentageUploaded += 0.0000000004;
print(pourcentageUploaded);
setstate(() {});
} while (pourcentageUploaded < 1);
pourcentageUploaded = 0.4;
setstate(() {});
},
),
Center(
child: Text(fileUploaded
? 'Telechargement...'
: 'Veuillez glisser le document ici'),
),
Container(
child: Container(
decoration: BoxDecoration(
color: Colors.transparent),
height: 50,
width: 500,
child: Center(
child: AnimatedContainer(
duration: Duration(seconds: 1),
color: Colors.yellow[100],
height: 50,
width: pourcentageUploaded * 500,
),
),
),
)
],
),
),
),
));

Flutter is not clearing rendered widgets, only re-painting

I am having a Scaffold with a floatingActionButton. Inside I have an inappwebview which displays some webpage. The floatingActionButton is displayed in the front above the webview. Also I show some dialog for a second.
Everything worked fine until yesterday. I upgraded flutter and I suddenly experienced weird behaviour which is why i downgraded flutter again. But I still got the same problem. All the stuff that is rendered above is never cleared and just re-painted all the time, which leads to dark shadows and never disappearing dialog windows.
Here you can see the dark shadow around the floatingActionButton and the bottomBar. Also the "<3 + Karma" badge does not disappear anymore.
The weird thing is, that I did not change anything. On my other machine everything still builds fine. There I use the same code, same package versions in my pubspec.yaml and also the same flutter/dart version.
I am really puzzled here. I can't seem to build a new app version without this bug on my main desktop machine.
This is my currently used flutter version:
Flutter 2.10.2 • channel unknown • unknown source
Framework • revision 097d3313d8 (3 months ago) • 2022-02-18 19:33:08 -0600
Engine • revision a83ed0e5e3
Tools • Dart 2.16.1 • DevTools 2.9.2
flutter doctor tells me, No issues found!
This is my code for reference:
return WillPopScope(
onWillPop: ArticleHandler().backButtonPressed,
child: Scaffold(
floatingActionButton: Visibility(
visible: _fabIsVisible,
child: FloatingActionButton(
onPressed: () {
webView.scrollTo(x: 0, y: 0, animated: true);
},
child: Icon(
Icons.arrow_upward,
color: Colors.white,
),
backgroundColor: Theme.of(context).primaryColor,
)),
floatingActionButtonLocation: MarginEndFloatFABLocation(),
floatingActionButtonAnimator: NoFABAnimation(),
appBar: TopBar(widget.articlePreview.url),
body: Builder(builder: (BuildContext context) {
return Container(
child: Column(
children: <Widget>[
progress < 1.0
? Container(
height: 3,
child: LinearProgressIndicator(
value: progress,
backgroundColor: Colors.white,
valueColor: AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColor),
))
: Container(height: 0),
Expanded(
child: InAppWebView(
initialOptions: InAppWebViewGroupOptions(
android: AndroidInAppWebViewOptions(useHybridComposition: true),
crossPlatform: InAppWebViewOptions(
//cacheEnabled: false, // uncomment this line to clean cache on open
)),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onProgressChanged: (InAppWebViewController controller, int progress) {
setState(() {
this.progress = progress / 100;
});
},
onOverScrolled: (InAppWebViewController controller, int x, int y, bool clampedX, bool clampedY) {
// maybe show karma badge
},
onScrollChanged: (InAppWebViewController controller, int x, int y) async {
if (y > 0) {
if (!_fabIsVisible) {
setState(() {
_fabIsVisible = true;
});
}
} else {
if (_fabIsVisible) {
setState(() {
_fabIsVisible = false;
});
}
}
})),
BottomTagBar(),
],
));
}),
));

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),
)

Issue with external keyboard emulation with usb RFID Reader

I have a RFID Reader which emulates keyboard input. I want get card number with it in my flutter application and then submit to api. I have tried onChanged Event but it fires before the reader could sent all the card numbers. If I try it with onSubmitted, this never fires because the Reader emulates Carriage Return after typing all card digits. Please help
I have tried onChanged which fires as soon as first digit is printed by reader which is wrong as I need all digits and also onSubmitted never fires because it doesn't work with external keyboard Enter Key. Also I have tried RawKeyboardListener, but then all key strokes are sent to RawKeyboardListener and there is no input to send in TextBox.
I expect once all card digits are read be reader and sent to TextBox, then it should be submitted to api automatically and not on button click as Submit Button.
class _TagCardState extends State<TagCard> {
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
final cardController = new TextEditingController();
final focusNode = new FocusNode();
final keyboardNode = new FocusNode();
StudentData currentStudent = StudentData(name: "Ready to Tag");
final TextStyle h1 = TextStyle(fontSize: 20.0);
final TextStyle h2 = TextStyle(fontSize: 16.0);
#override
void initState(){
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => afterFirstLayout(context));
keyboardNode.addListener((){
if(keyboardNode.hasFocus){
print("keyboard focused");
}
});
focusNode.addListener((){
if(keyboardNode.hasFocus){
print("texbox focused");
}
});
}
#override
void dispose(){
cardController.dispose();
focusNode.dispose();
keyboardNode.dispose();
super.dispose();
}
void afterFirstLayout(BuildContext context) {
FocusScope.of(context).requestFocus(keyboardNode);
}
void _handleKeyEvent(RawKeyEvent key) {
final _kEnter = 66;
if (key is RawKeyDownEvent && key.data is RawKeyEventDataAndroid) {
RawKeyDownEvent ev = key;
RawKeyEventDataAndroid evAndroid = ev.data;
print(evAndroid.keyCode);
if(evAndroid.keyCode == _kEnter){
print("Enter Key");
print("Text box value :" + cardController.text);
// FocusScope.of(context).requestFocus(focusNode);
}
}
}
void resetStudentData() {
this.setState((){
this.currentStudent = StudentData(name: "Ready to Tag");
FocusScope.of(context).requestFocus(keyboardNode);
});
}
void showLoading() {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
title: Center(child:CircularProgressIndicator()),
content: Container(
alignment: AlignmentDirectional.center,
height: 50.0,
child: Text("Loading...")
),
),
);
}
void sendRequest(cardNumber) async {
final data = {
"card_number" : cardNumber
};
focusNode.unfocus();
this.showLoading();
httpPut("student/card/tag", data).then((response) {
cardController.clear();
Navigator.of(context).pop();
Map responseData = json.decode(response);
print(responseData);
if(responseData['success']){
this.setState((){
this.currentStudent = StudentData(
name: responseData['data']['student_name'],
cls: responseData['data']['class'],
rollNumber: responseData['data']['roll_number'],
image: responseData['data']['image'],
in_out: responseData['data']['in_out'].toUpperCase()
);
FocusScope.of(context).requestFocus(keyboardNode);
new Future.delayed(new Duration(seconds: 3), resetStudentData);
});
}
else {
FocusScope.of(context).requestFocus(keyboardNode);
_scaffoldKey.currentState.showSnackBar(
SnackBar(
content: Text(responseData['message']),
backgroundColor: Colors.red,
)
);
}
});
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text("KMV Attandence"),
),
body: Container(
alignment: AlignmentDirectional.center,
padding: EdgeInsets.all(20.0),
child: Form(
key: _formKey,
child: Center(
child: ListView(
shrinkWrap: true,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RawKeyboardListener(
child: TextField(
enabled: true,
obscureText: false,
controller: cardController,
onSubmitted: (text) => this.sendRequest(text),
textAlign: TextAlign.center,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Tag Card'
),
),
focusNode: keyboardNode,
onKey: (key) => _handleKeyEvent(key),
),
Text(this.currentStudent.name, style: this.h1),
Text(this.currentStudent.cls, style: this.h2),
Text(this.currentStudent.rollNumber, style: this.h2),
Container(
decoration: BoxDecoration(
color: Colors.green
),
child: Text(this.currentStudent.in_out, style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
)),
)
],
),
]
)
)
)
)
);
}
}
class StudentData {
final String name;
final String cls;
final String rollNumber;
final String image;
final String in_out;
const StudentData({
this.name = "",
this.cls = "",
this.rollNumber = "",
this.image = "",
this.in_out = ""
});
[√] Flutter (Channel beta, v1.0.0, on Microsoft Windows [Version 10.0.17134.471], locale en-IN)
• Flutter version 1.0.0 at C:\flutter
• Framework revision 5391447fae (6 weeks ago), 2018-11-29 19:41:26 -0800
• Engine revision 7375a0f414
• Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)
[√] Android toolchain - develop for Android devices (Android SDK 28.0.3)
• Android SDK at C:\Android\Sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-28, build-tools 28.0.3
• ANDROID_HOME = C:\Android\Sdk
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02)
• All Android licenses accepted.
[√] Android Studio (version 3.1)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 29.0.1
• Dart plugin version 173.4700
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02)
[√] Connected device (1 available)
• Android SDK built for x86 64 • emulator-5554 • android-x64 • Android 8.0.0 (API 26) (emulator)
• No issues found!