My setup:
class Start_Page extends StatefulWidget {
#override
StartPageState createState() => StartPageState();
}
class StartPageState extends State<Start_Page> {
#override
Widget build(BuildContext context){
return Scaffold(
body: Container(
child: ElevatedButton(
style: ButtonStyle(),
onPressed: () {
createUserModalBottomSheet(context);
},
child: Text("Start"),
)
)
);
}
}
void createUserModalBottomSheet(context){
showModalBottomSheet(context: context, builder: (BuildContext bc) {
return Container(
child: Switch(value: true, onChanged: (value) => {value = !value}, activeColor:
Colors.grey)
);
}
}
The Problem is that the switch won't change his value. The Modalbottomsheet appears but won't update changes/states.
Does anyone know a solution?
Use StatefulBuilder to update UI inside showModalBottomSheet. Second issue is you need to use a bool variable to hold value.
class StartPageState extends State<Start_Page> {
bool switchValue = false;
///......
void createUserModalBottomSheet(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return StatefulBuilder(
builder: (context, setStateSB) => Container(
child: Switch(
value: switchValue,
onChanged: (value) {
setState(() {
// update parent UI
switchValue = value;
});
setStateSB(() {
// update inner dialog
switchValue = value;
});
},
activeColor: Colors.grey),
),
);
});
}
#override
Widget build(BuildContext context) {
.........
Related
I have this page
I want when Scroll reach the end, load more data from server.
my Code is here:
class MyProfilePage extends StatefulWidget {
late String storeCode;
bool hasBack = true;
MyProfilePage(this.storeCode, this.hasBack);
#override
_MyProfilePageState createState() => _MyProfilePageState();
}
class _MyProfilePageState extends State<MyProfilePage>
with SingleTickerProviderStateMixin {
late TabController _tabController;
late ScrollController _scrollController;
bool finish = false;
int page = 1;
#override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
_scrollController = ScrollController();
context.read<FavoriteListCubit>().getPostList(widget.storeCode);
context.read<PostsListCubit>().getPostList(widget.storeCode);
context.read<TagMenuCubit>().getTagMenuList(widget.storeCode);
// }
_scrollController.addListener(() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
if (mounted) {
if (!finish) {
////this condition check if not requested,request again
if (context.read<PostsListCubit>().state is! PostsMoreListLoading) {
print("pageeee");
page = page + 1;
context.read<PostsListCubit>().getMorePostList(widget.storeCode,page);
}
}
}
} else {}
});
}
#override
void dispose() {
_tabController.dispose();
_scrollController.dispose();
super.dispose();
}
late BuildContext ctx;
Widget? header;
Widget? body_;
#override
Widget build(BuildContext context) {
ctx = context;
body_ ??= buildProfile(context);
return body_!;
}
Widget buildProfile(BuildContext context) {
return Scaffold(
appBar: widget.hasBack ? MyAppBar().appBarFirstMenu("title_", context, widget.hasBack) : null,
body: SafeArea(
child: Directionality(
textDirection: TextDirection.ltr,
child: DefaultTabController(
length: _tabController.length,
child: RefreshIndicator(
notificationPredicate: (notification) {
return notification.depth == 2;
},
onRefresh: () async {
context.read<StoreInfoCubit>().getStoreInfo(widget.storeCode);
context.read<PostsListCubit>().getPostList(widget.storeCode);
context.read<TagMenuCubit>().getTagMenuList(widget.storeCode);
return context.read<FavoriteListCubit>().getPostList(widget.storeCode);
},
child: NestedScrollView(
controller: _scrollController,
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return [
SliverToBoxAdapter(
child: header ?? (header = MyInfo(
storeCode: widget.storeCode,
))),
SliverPersistentHeader(
delegate: _CustomSliverDelegate(_tabController),
pinned: true,
floating: true,
),
];
},
body: TabBarView(
controller: _tabController,
children: [
PostListGridView(storeCode:widget.storeCode),
PlayListGridView(storeCode: widget.storeCode),
FavoriteListGridView(storeCode:widget.storeCode),
],
),
),
),
),
),
),
);
}
Widget playTab() {
return Center( child: SingleChildScrollView(
child: Text(MyString.commingSoon),
),
);
}
}
class _CustomSliverDelegate extends SliverPersistentHeaderDelegate {
TabController _tabController;
_CustomSliverDelegate(this._tabController);
#override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
return Container(
height: 50.0,
color: Colors.grey[50],
child: TabBar(
controller: _tabController,
tabs: const [
Icon(Icons.grid_on),
Icon(CupertinoIcons.play),
Icon(FontAwesome.bookmark_empty),
],
),
);
}
#override
double get maxExtent => 50.0;
#override
double get minExtent => 50.0;
#override
bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
return false;
// throw UnimplementedError();
}
}
I try set controller for NestedScrollView but not Working good, try to set Controller for GridView this way relatively good but causes that page has two Scroll.(once for nestedScrollView and once for gridview)
how to solve this problem?
Hello fellow Flutter Devs
I am pretty new to Flutter and I am building a bottom navigation bar with three pages and on one page the will be a list with items from an API using the bloc architecture. However I am getting the error in the title located to the ListPage().
ProviderNotFoundException (Error: Could not find the correct Provider above this ListPage Widget
ListPage():
class ListPage extends StatelessWidget {
const ListPage({super.key});
#override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => ListCubit(
repository: context.read<ListRepository>(),
)..fetchList(),
child: const ItemListView(),
);
}
}
class ItemListView extends StatelessWidget {
const ItemListView({super.key});
#override
Widget build(BuildContext context) {
final state = context.watch<ListCubit>().state;
switch (state.status) {
case ListStatus.failure:
return const Center(child: Text('Oops something went wrong!'));
case ListStatus.success:
return ItemView(items: state.items);
case ListStatus.loading:
return const Center(child: CircularProgressIndicator());
}
}
}
class ItemView extends StatelessWidget {
const ItemView({super.key, required this.items});
final List<Item> items;
#override
Widget build(BuildContext context) {
return items.isEmpty
? const Center(child: Text('no content'))
: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return ItemTile(
item: items[index],
);
},
itemCount: items.length,
);
}
}
class ItemTile extends StatelessWidget {
const ItemTile({
super.key,
required this.item,
});
final Item item;
#override
Widget build(BuildContext context) {
return Material(
child: ListTile(
leading: Text('#${item.id}'),
title: Text(item.position),
),
);
}
}
The ListPage() is in the HomePage():
class HomePage extends StatelessWidget {
const HomePage({super.key});
static Route<void> route() {
return MaterialPageRoute<void>(builder: (_) => const HomePage());
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: BlocBuilder<BottomNavigationBloc, BottomNavigationState>(
builder: (BuildContext context, BottomNavigationState state) {
if (state is PageLoading) {
return Center(child: CircularProgressIndicator());
}
if (state is ListPageLoaded) {
return ListPage();
}
if (state is SettingsPageLoaded) {
return SettingsPage(
biometrics: state.biomentrics,
version: state.version,
env: state.env,
);
}
return Container();
},
),
bottomNavigationBar:
BlocBuilder<BottomNavigationBloc, BottomNavigationState>(
builder: (BuildContext context, BottomNavigationState state) {
return BottomNavigationBar(
...
And last but not least, my app.dart:
class App extends StatelessWidget {
const App({
super.key,
required this.authenticationRepository,
required this.userRepository,
required this.listRepository,
required this.settingsRepository,
});
final AuthenticationRepository authenticationRepository;
final UserRepository userRepository;
final ListRepository listRepository;
final SettingsRepository settingsRepository;
#override
Widget build(BuildContext context) {
return RepositoryProvider.value(
value: authenticationRepository,
child: MultiBlocProvider(
providers: [
BlocProvider(
create: (_) => AuthenticationBloc(
authenticationRepository: authenticationRepository,
userRepository: userRepository,
),
),
BlocProvider(
create: (_) => BottomNavigationBloc(
listPageRepository: listRepository,
settingsPageRepository: settingsRepository))
],
child: const AppView(),
));
}
}
class AppView extends StatefulWidget {
const AppView({super.key});
#override
State<AppView> createState() => _AppViewState();
}
class _AppViewState extends State<AppView> {
final _navigatorKey = GlobalKey<NavigatorState>();
NavigatorState get _navigator => _navigatorKey.currentState!;
#override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: _navigatorKey,
builder: (context, child) {
return BlocListener<AuthenticationBloc, AuthenticationState>(
listener: (context, state) {
switch (state.status) {
case AuthenticationStatus.authenticated:
_navigator.pushAndRemoveUntil<void>(
HomePage.route(),
(route) => false,
);
break;
case AuthenticationStatus.unauthenticated:
_navigator.pushAndRemoveUntil<void>(
LoginPage.route(),
(route) => false,
);
break;
case AuthenticationStatus.unknown:
break;
}
},
child: child,
);
},
onGenerateRoute: (_) => SplashPage.route(),
);
}
}
As the error says it could not find the right provider I probably need to add it somewhere in my project but i don't know where because I added the ListRepository in my App(). Do I need to add in the _AppViewState() as well?
Thanks for your help and I will give additional information in the comments if you need so.
I'm starting on Flutter. Today, I learned how to coding a showDialog, but it doesn't work. i have tried to write it again and again but nothing affects... here's my code:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: Scaffold(appBar: AppBar(), body: MyHome())));
}
class MyHome extends StatefulWidget {
const MyHome({Key? key}) : super(key: key);
#override
State<MyHome> createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
#override
void MyDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("title"),
content: Text("Thanks to clock"),
actions: <Widget>[
TextButton(
onPressed: () {},
child: Text("close"),
)
],
);
});
}
Widget build(BuildContext context) {
return TextButton(
onPressed: () {},
child: Text("Click On me!"),
);
}
}
Please help me! Thanks...
You did not call MyDialog anywhere in the code.
updated code:
import 'package:flutter/material.dart';
class SignUpScreen extends StatefulWidget {
const SignUpScreen({Key? key}) : super(key: key);
#override
State<SignUpScreen> createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
#override
void MyDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("title"),
content: Text("Thanks to clock"),
actions: <Widget>[
TextButton(
onPressed: () {},
child: Text("close"),
)
],
);
});
}
Widget build(BuildContext context) {
return TextButton(
onPressed: () {
MyDialog();
},
child: Text("Click On me!"),
);
}
}
The problem is that you are do not invoke dialog-function by you button. Rename dialog-function accordingly to the code-convention, for example 'showMyDialog' and then invoke it:
return TextButton(
onPressed: () => showMyDialog(),
child: Text("Click On me!"),
);
So I have this code and I take an image from Internet with webscrapper, the problem is that when I try to take the image with the basic URl without the http:// behind it don't work and when I add it I don't have any error but I got a black screen on my emulator and I can't see this value of the image on my terminal even if I know the value is not null.
If someone can help I will be very greatful thank you very much !
class ContentScreen extends StatefulWidget {
const ContentScreen({Key? key}) : super(key: key);
#override
_ContentScreenState createState() => _ContentScreenState();
}
class _ContentScreenState extends State<ContentScreen> {
List<Map<String,dynamic>>? contentPages;
bool Data = false;
Future<void> getcontent() async{
final webscraper = WebScraper("https://manhuas.net/");
String TempRoute = "manhua/what-harm-would-my-girl-do-manhua/what-harm-would-my-girl-do-chapter-1/";
if (await webscraper.loadWebPage(TempRoute)){
contentPages = webscraper.getElement("div.page-break.no-gaps > img ", ["data-src"]);
setState(() {
Data = true;
});
print(contentPages);
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
getcontent();
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: getcontent(),
builder: (context, snapshot) {
return Scaffold(
body: Data? Container(
child: ListView.builder(
shrinkWrap: true,
itemCount: contentPages!.length,
itemBuilder: (context,index ) {
return Image.network(contentPages![index]['attributes']['src'].toString().trim(),
fit: BoxFit.fitWidth,loadingBuilder: (context , child, loadingprogress){
if (loadingprogress != null) return child;
return Center(
child: CircularProgressIndicator(),
);
},);
},
)
)
: Center(
child: CircularProgressIndicator(
color: Constants.mygreen,
)
));
}
);
}
}
And this is a screen of my screen for more details:
Please check the below code it's working perfectly
import 'package:flutter/material.dart';
import 'package:web_scraper/web_scraper.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'OverlayEntry Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: ContentScreen(),
);
}
}
class ContentScreen extends StatefulWidget {
const ContentScreen({Key? key}) : super(key: key);
#override
_ContentScreenState createState() => _ContentScreenState();
}
class _ContentScreenState extends State<ContentScreen> {
List<Map<String, dynamic>>? contentPages;
bool Data = false;
Future<void> getcontent() async {
final webscraper = WebScraper("https://manhuas.net/");
String TempRoute =
"manhua/what-harm-would-my-girl-do-manhua/what-harm-would-my-girl-do-chapter-1/";
if (await webscraper.loadWebPage(TempRoute)) {
contentPages =
webscraper.getElement("div.page-break.no-gaps > img ", ["data-src"]);
setState(() {
Data = true;
});
print(contentPages);
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
getcontent();
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: getcontent(),
builder: (context, snapshot) {
return Scaffold(
body: Data
? Container(
child: ListView.builder(
shrinkWrap: true,
itemCount: contentPages!.length,
itemBuilder: (context, index) {
return Image.network(
contentPages![index]['attributes']
['data-src']
.toString()
.trim(),
fit: BoxFit.fitWidth,
);
},
))
: Center(
child: CircularProgressIndicator(
color: Colors.green,
)));
});
}
}
I need to pause camera when I move to another screen on the navigator tree in order to save battery and performance.
I tried to dispose() cameraController, but flutter doesn't re-initialize the state when it returns from another screen (which is obvious, though).
My main code to work with a camera:
#override
void initState() {
super.initState();
availableCameras().then((cameras) {
setState(() {
_firstCamera = cameras.first;
_controller = CameraController(_firstCamera, ResolutionPreset.high);
_initializeControllerFuture = _controller.initialize();
});
});
}
#override
void dispose() {
_controller?.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
body: Stack(
children: <Widget>[
FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Stack(
alignment: FractionalOffset.center,
children: <Widget>[
new Positioned.fill(
child: _getCameraPreview(context),
),
...
],
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
Align(
alignment: Alignment.bottomCenter,
child: BottomAppBar(
color: Color.fromARGB(0, 0, 0, 0),
child: _getBottomAppBarRow(context),
),
),
],
),
);
}
_getCameraPreview(BuildContext context) {
final size = MediaQuery.of(context).size;
final deviceRatio = size.width / size.height;
return Transform.scale(
scale: _controller.value.aspectRatio / deviceRatio,
child: Center(
child: AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: CameraPreview(_controller),
),
),
);
}
Have a variable like _cameraOn = true. Show CameraPreview when it is true and not when it is false. While navigating to another screen set it to false
You could have the camera related functionality in a separate widget. So every time it is displayed it is initialized, and when it is not it's disposed.
A simple working example
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras;
Future<void> main() async {
cameras = await availableCameras();
runApp(MaterialApp(
home: CameraApp(),
));
}
class CameraApp extends StatefulWidget {
#override
_CameraAppState createState() => _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
bool _cameraOn = true;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Expanded(
child: _cameraOn ? Camera() : Container(),
),
FlatButton(
onPressed: () {
setState(() {
_cameraOn = false;
});
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => Post())).then((res) {
setState(() {
_cameraOn = true;
});
}).catchError((err) {
print(err);
});
},
child: Text("NEXT PAGE"),
),
],
),
);
}
}
class Camera extends StatefulWidget {
#override
_CameraState createState() => _CameraState();
}
class _CameraState extends State<Camera> {
CameraController controller;
#override
void initState() {
super.initState();
controller = CameraController(cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
#override
Widget build(BuildContext context) {
if (!controller.value.isInitialized) {
return Container();
}
return AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: CameraPreview(controller),
);
}
#override
void dispose() {
controller?.dispose();
super.dispose();
}
}
class Post extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Text("Post"),
);
}
}
Suppose the camera controller for an instance of the camera package is defined as such:
List<CameraDescription> cameras = [];
controller = CameraController(
cameras[0],
ResolutionPreset.high,
enableAudio: false,
);
This can be used to pause the camera:
controller.pausePreview();
This can be used to resume the camera:
controller.resumePreview();