I have a demo app and the Internationalization is not working correctly.
My time code is +3 (North Cyprus). Language is TR. Date part works for TR.
but time is not working. Example instead of showing 08:27:18 it shows 05:27.18 GMT time.
More info: https://greenwichmeantime.com/time-zone/europe/turkey/
Examples: https://github.com/NTMS2017/Internationalization
Any help please?
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Internationalization',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Internationalization'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
DateFormat dateFormat;
DateFormat timeFormat;
#override
void initState() {
super.initState();
initializeDateFormatting();
dateFormat = new DateFormat.yMMMMd('tr_TR');
timeFormat = new DateFormat.Hms('tr_TR');
}
void _refresh() {
setState(() {});
}
#override
Widget build(BuildContext context) {
var dateTime = new DateTime.now();
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
backgroundColor: Colors.pinkAccent,
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(dateFormat.format(dateTime),
style: new TextStyle(
fontSize: 24.0,
fontWeight: FontWeight.bold,
color: Colors.pinkAccent,
),
),
new Text(timeFormat.format(dateTime),
style: new TextStyle(
fontSize: 22.0,
fontWeight: FontWeight.bold
),
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _refresh,
tooltip: 'Refresh',
child: new Icon(Icons.refresh),
),
);
}
}
With #GünterZöchbauer help. I check my android simulator.
My Simulator is Nexus 5X API 26.
Setting the simulator Language to TR and Region to Turkey the above code works well.
Related
I'm new to flutter and in my new project I've created a welcome screen that have 2 buttons either login or sign up , I'm using a Wrapper for the authentication and a toggle to navigate between login and sign up ... every thing works fine , but once the app lunches it shows the login screen not the welcome screen !
here is my wrapper class
class wrapper extends StatelessWidget {
const wrapper({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final userModel = Provider.of<UserModel?>(context);
// either home or login page
if(userModel == null){
return const Authenticate();
}else{
return const Home();
}
}
}
and here is my main
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 StreamProvider<UserModel?>.value(
initialData: null,
value: Authentication().onAuthStateChanged,
builder: (context, snapshot) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Auth',
theme: ThemeData(
primaryColor: kPrimaryColor,
scaffoldBackgroundColor: Colors.white,
textTheme: GoogleFonts.nunitoTextTheme(),
),
home: wrapper(),
);
}
);
}
}
the authenticate class :
class Authenticate extends StatefulWidget {
const Authenticate({Key? key}) : super(key: key);
#override
_AuthenticateState createState() => _AuthenticateState();
}
class _AuthenticateState extends State<Authenticate> {
bool showSignIn = true ;
void toggleView() {
setState(() {
showSignIn = !showSignIn;
});
}
#override
Widget build(BuildContext context) {
if(showSignIn){
return LoginScreen(toggleView : toggleView);
}else{
return SignUpScreen(toggleView : toggleView);
}
}
}
welcome screen :
class WelcomeScreen extends StatelessWidget {
const WelcomeScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const Scaffold(
body: Body(),
);
}
}
Body :
class Body extends StatelessWidget {
const Body({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Container(
height: size.height,
width: double.infinity,
color: Color(0xFFA9D7CC),
child:Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(width: size.width,height: 70),
SvgPicture.asset(
"assets/images/recycle.svg" ,
width:441.4,
height: 294 ,
),
const Padding(
padding: EdgeInsets.fromLTRB(20, 40, 7, 0),
child:
Text("lets make saving the planet easy !",
style: TextStyle(
fontSize: 48 ,
fontWeight: FontWeight.bold,
color: Colors.white
),
),
),
const Padding(
padding: EdgeInsets.fromLTRB(27, 10, 110, 0),
child:
Text("start recycling and earn some money ",
style: TextStyle(
fontSize: 20 ,
fontWeight: FontWeight.normal,
color: Colors.white
),
),
),
SizedBox(width: size.width,height: 70),
// login button
SizedBox(
width: 297,
height: 71,
child: ElevatedButton(
style:ElevatedButton.styleFrom(
primary: kPrimaryPopColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40)
)
) ,
onPressed: (){},
child: const Text("login",
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold
),)),
),
//sign up button
SizedBox(
height: 70,
child: TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
),
onPressed: () {},
child: const Text('sign up',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),),
),
)
],
),
);
}
}
Your code in not full. Try to debug
https://docs.flutter.dev/development/tools/devtools/debugger
It seems to me, that here is true
if(userModel == null){
return const Authenticate();
[![enter image description here][1]][1]
I need to do it like this here:
[1]: https://i.stack.imgur.com/bNdZ3.png
But I can't do it. I tried some stuff but it doesn't work. Here is my main.dart below. I created the showImage method for showing image, I also applied it by Image.network(url); code but it didn't work,so I commented it.
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.red,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
var url;
void _incrementCounter() {
setState(() {
_counter++;
});
}
void showImage() async {
final ref = FirebaseStorage.instance.ref().child('erkekyuz');
// no need of the file extension, the name will do fine.
url = await ref.getDownloadURL();
print(url);
}
Widget _buildListItem(BuildContext context, DocumentSnapshot document) {
String mezunD;
if (document.data()['mezunDurumu'] == false) {
mezunD = "mezun değil";
}
if (document.data()['mezunDurumu'] == true) {
mezunD = "mezun değil";
}
var listTile = ListTile(
title: Column(
children: [
Expanded(
child: Text(
"Ad Soyad: " + document.data()['adSoyad'],
),
),
Expanded(
child: Text(
"Yaş: " + document.data()['yas'].toString(),
),
),
Expanded(
child: Text(
"Doğum Tarihi: " + document.data()['dogumTarihi'],
),
),
Expanded(
child: Text("Mezun Durumu: " + mezunD),
),
//Image.network(url),
//this didn't work somehow.
],
),
);
return listTile;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Öğrenci Durumu"),
),
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection('tablolar').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text('Loading...');
return ListView.builder(
itemExtent: 100.0,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) =>
_buildListItem(context, snapshot.data.documents[index]),
);
}),
);
}
}
Is your url variable showing any value?
Call your showImage() method like this to load image.
#override
void initState() {
super.initState();
showImage();
}
for showing images you can use :https://pub.dev/packages/cached_network_image
I am using a package called lit_firebase_auth which makes firebase authentication easier to handle. I want to be able to save user data, such as the username after the user logs in. Basically as such:
User logs in or signs up --> User clicks on edit profile page from the home screen --> User can enter their desired name in the text field and click save --> Saves this data to the cloud of the respectful logged in user.
Please I'm a beginner and I have no idea how to pull this off.
Here is the code for reference:
cloud_firebase.dart:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
Future<void> userSetup(String displayName) async {
CollectionReference users = FirebaseFirestore.instance.collection('Users');
FirebaseAuth auth = FirebaseAuth.instance;
String uid = auth.currentUser.uid.toString();
users.add({'displayName': displayName, 'uid': uid});
return;
}
auth.dart
import 'package:flutter/material.dart';
import 'package:kiwi/screens/auth/register.dart';
import 'package:kiwi/screens/background_painter.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/auth/sign_in.dart';
import 'package:animations/animations.dart';
import 'package:kiwi/screens/home.dart';
class AuthScreen extends StatefulWidget {
const AuthScreen({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const AuthScreen(),
);
#override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen>
with SingleTickerProviderStateMixin {
AnimationController _controller;
ValueNotifier<bool> showSignInPage = ValueNotifier<bool>(true);
#override
void initState() {
_controller =
AnimationController(vsync: this, duration: const Duration(seconds: 2));
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: LitAuth.custom(
onAuthSuccess: () {
Navigator.of(context).pushReplacement(HomeScreen.route);
},
child: Stack(
children: [
SizedBox.expand(
child: CustomPaint(
painter: BackgroundPainter(),
)),
Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 800),
child: ValueListenableBuilder<bool>(
valueListenable: showSignInPage,
builder: (context, value, child) {
return PageTransitionSwitcher(
reverse: !value,
duration: Duration(milliseconds: 800),
transitionBuilder:
(child, animation, secondaryAnimation) {
return SharedAxisTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
transitionType: SharedAxisTransitionType.vertical,
fillColor: Colors.transparent,
child: child,
);
},
child: value
? SignIn(
key: ValueKey('SignIn'),
onRegisterClicked: () {
context.resetSignInForm();
showSignInPage.value = false;
_controller.forward();
},
)
: Register(
key: ValueKey('Register'),
onSignInPressed: () {
context.resetSignInForm();
showSignInPage.value = true;
_controller.reverse();
},
),
);
},
),
),
),
],
),
),
);
}
}
splash.dart
import 'package:flutter/material.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/home.dart';
import 'package:kiwi/screens/auth/auth.dart';
class SplashScreen extends StatelessWidget {
const SplashScreen({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const SplashScreen(),
);
#override
Widget build(BuildContext context) {
final user = context.watchSignedInUser();
user.map(
(value) {
_navigateToHomeScreen(context);
},
empty: (_) {
_navigateToAuthScreen(context);
},
initializing: (_) {},
);
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
void _navigateToAuthScreen(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.of(context).pushReplacement(AuthScreen.route),
);
}
void _navigateToHomeScreen(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.of(context).pushReplacement(HomeScreen.route),
);
}
}
edit_profile.dart
import 'package:flutter/material.dart';
import 'package:kiwi/config/palette.dart';
import 'package:kiwi/screens/auth/decoration_functions.dart';
class Profile extends StatefulWidget {
const Profile({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const Profile(),
);
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
// UserModel _currentUser = locator.get<UserController>().currentUser;
// File _image;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Edit Profile'),
),
body: Builder(
builder: (context) => Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 20.0,
),
Column(
children: <Widget>[
Text(
'Hey there',
style: TextStyle(color: Palette.lightGreen, fontSize: 20),
)
],
),
SizedBox(
height: 20,
),
Expanded(
flex: 8,
child: ListView(
children: [
Padding(
padding: EdgeInsets.fromLTRB(50, 0, 50, 0),
child: TextFormField(
style: const TextStyle(
fontSize: 18,
color: Colors.green,
),
decoration: signInInputDecoration(
hintText: 'New Username',
),
),
),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
elevation: 4,
color: Colors.red,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'Cancel',
style: TextStyle(color: Colors.white),
),
),
RaisedButton(
elevation: 4,
color: Palette.lightGreen,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'Save',
style: TextStyle(color: Colors.white),
),
),
],
),
],
),
),
],
),
),
),
);
}
}
to save user data to document in firebase using uuid for document name the below code will work.
if you are confused about how to use the code in your app its simple.
just follow the steps:
call userSetup Function from onpress while passing the display name data.
how to use
the below code will create new document using the currect users uuid in firestore in user collection and save the data.
onPress:(){
userSetup(displayName:"zakriakhan");
}
userSteup Function
Future<void> userSetup(String displayName) async {
//firebase auth instance to get uuid of user
FirebaseAuth auth = FirebaseAuth.instance.currentUser();
//now below I am getting an instance of firebaseiestore then getting the user collection
//now I am creating the document if not already exist and setting the data.
FirebaseFirestore.instance.collection('Users').document(auth.uid).setData(
{
'displayName': displayName, 'uid': uid
})
return;
}
I'm using a method of searching for an api but I'm not managing to pass the information I get to the Widget that renders it and get the data I all well
Header search Widget:
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:movies/Movies/bloc/blocmovies.dart';
import 'package:movies/Movies/model/findmoviemodel.dart';
import 'package:movies/Movies/ui/widgets/gridview_search_screen.dart';
class HeaderSearchScreen extends StatefulWidget with PreferredSizeWidget {
HeaderSearchScreen({Key key}) : super(key: key);
#override
_HeaderSearchScreenState createState() => _HeaderSearchScreenState();
#override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}
class _HeaderSearchScreenState extends State<HeaderSearchScreen> {
BlocMovies blocMovies;
final TextEditingController _controller = TextEditingController();
Widget appBarTitle() {
return TextField(
onSubmitted: searchOperation,
autofocus: true,
controller: _controller,
style: TextStyle(
color: Colors.black,
),
decoration: InputDecoration(
suffix: IconButton(
icon: Icon(Icons.cancel),
onPressed: () {
Future.delayed(Duration(milliseconds: 50)).then((_) {
_controller.clear();
FocusScope.of(context).unfocus();
});
},
),
hintText: "Buscar",
hintStyle: TextStyle(color: Colors.grey.withOpacity(0.5))),
);
}
#override
Widget build(BuildContext context) {
blocMovies = BlocProvider.of(context);
return buildAppBar(context);
}
Widget buildAppBar(BuildContext context) {
return AppBar(
iconTheme: IconThemeData(color: Colors.black),
backgroundColor: Colors.white,
centerTitle: true,
title: this.appBarTitle());
}
searchOperation(String searchText) {
blocMovies.findMovies(searchText)
.then((data){
if(data.results.length == 0){
print("no se encontro");
showDialog(
context: context,
child: AlertDialog(
title: const Text("No se encontro la pelicula"),
actions: [
FlatButton(
child: const Text("Ok"),
onPressed: () => Navigator.pop(context),
),
],
),
);
}else{
setState(() {
print(data.results);
GridViewSearchScreen(listsearchmovieOne: data.results);
});
}
})
.catchError((){
print("Hubo un error");
});
}
}
/*
blocMovies.findMovies(searchText)
.then((data){
if(data.results.length == 0){
print("no se encontro");
showDialog(
context: context,
child: AlertDialog(
title: const Text("No se encontro la pelicula"),
actions: [
FlatButton(
child: const Text("Ok"),
onPressed: () => Navigator.pop(context),
),
],
),
);
}else{
//Here trying pass datan and debug console a get snapshot
GridViewSearchScreen(listsearchmovieOne: data.results);
}
})
.catchError((){
print("Hubo un error");
});
GridViewSearch:
import 'package:animate_do/animate_do.dart';
import 'package:flutter/material.dart';
import 'package:movies/Movies/model/findmoviemodel.dart';
import 'package:movies/Movies/ui/widgets/cadsearchmovies.dart';
import 'package:movies/Widgets/Screen_Sizes/responsive_screens.dart';
class GridViewSearchScreen extends StatefulWidget {
List<Result> listsearchmovieOne;
double _crossAxisSpacing = 15, _mainAxisSpacing = 12, _aspectRatio = 1;
GridViewSearchScreen({Key key, this.listsearchmovieOne}) : super(key: key);
#override
_GridViewSearchScreenState createState() => _GridViewSearchScreenState(listsearchmovie: this.listsearchmovieOne );
}
class _GridViewSearchScreenState extends State<GridViewSearchScreen> {
List<Result> listsearchmovie;
_GridViewSearchScreenState({this.listsearchmovie});
#override
Widget build(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
double screenHeight = MediaQuery.of(context).size.height;
double _pixeRatio = MediaQuery.of(context).devicePixelRatio;
bool small = ResponsiveWidget.isScreenSmall(screenWidth, _pixeRatio);
bool medium = ResponsiveWidget.isScreenMedium(screenWidth, _pixeRatio);
bool large = ResponsiveWidget.isScreenLarge(screenWidth, _pixeRatio);
return (listsearchmovie == null)
? Center(
child: Container(
child: Text("No hay peliculas que mostrar"),
))
: Container(
margin: EdgeInsets.only(top: screenHeight * 0.2),
child: GridView.builder(
itemCount: listsearchmovie.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: (large) ? 4 : (medium) ? 2 : (small) ? 2 : 2,
crossAxisSpacing: widget._crossAxisSpacing,
mainAxisSpacing: widget._mainAxisSpacing,
childAspectRatio: (large)
? screenWidth / (screenHeight / 0.62)
: (medium)
? screenWidth / (screenHeight / 1.03)
: (small)
? screenWidth / (screenHeight / 1.03)
: screenWidth / (screenHeight / 1.03),
),
itemBuilder: (BuildContext context, int i) {
final movie = listsearchmovie[i];
print(movie.posterPath);
return FadeInLeft(
duration: Duration(milliseconds: 10 * i),
child: CardSearchinfoMovies(
movie: Result(
backdropPath: movie.backdropPath,
overview: movie.overview,
posterPath: movie.posterPath,
voteAverage: movie.voteAverage,
title: movie.title)),
);
}));
}
}
and on this screen is where together these two widgets
import 'package:flutter/material.dart';
import 'package:movies/Movies/ui/widgets/gridview_search_screen.dart';
import 'package:movies/Movies/ui/widgets/header_search_screen.dart';
class ScreenSearchMovies extends StatefulWidget {
#override
_ScreenSearchMoviesState createState() => _ScreenSearchMoviesState();
}
class _ScreenSearchMoviesState extends State<ScreenSearchMovies> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: HeaderSearchScreen(),
body: Stack(
children:<Widget>[
GridViewSearchScreen()
]
)
);
}
}
Any idea what might be going on already trying everything and I can't get the information displayed?
Try this way:
`....
....
class _GridViewSearchScreenState extends State<GridViewSearchScreen> {
List<Result> listsearchmovie = List<Result>();
_GridViewSearchScreenState({this.listsearchmovie});
.....
.....
`
Playing around with Flutter, I am trying to interact in one touch move with multiple elements. However my gesture is triggered only in first Container.
Is there any way to do this using GestureDetector or Listener classes?
I mean, is there any better solution than set Listener on parent element and calculate if current touch pointer position is between coordinates of child elements I want to recognize touch event?
Here is an example of code to illustrate the issue I am dealing with.
Swiping horizontaly, I would like to select all TapBox elements in Row.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Swipe select',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Swipe select'),
);
}
}
class TapBox extends StatefulWidget {
TapBox({Key key, this.bgColor}) : super(key: key);
Color bgColor;
#override
_TapBoxState createState() => new _TapBoxState();
}
class _TapBoxState extends State<TapBox> {
#override
Widget build(BuildContext context) {
return new Padding(
padding: new EdgeInsets.only(left: 10.0, right: 10.0),
child: new GestureDetector(
onPanUpdate: ((e) {
this.setState(() {
widget.bgColor = Colors.blueAccent;
});
}),
onPanStart: ((e) {
this.setState(() {
widget.bgColor = Colors.blueAccent;
});
}),
child: new Container(
width: 50.0,
height: 200.0,
color: widget.bgColor,
),
),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new TapBox(bgColor: Colors.grey),
new TapBox(bgColor: Colors.grey),
new TapBox(bgColor: Colors.grey),
new TapBox(bgColor: Colors.grey),
new TapBox(bgColor: Colors.grey),
],
),
),
);
}
}