Related
I have a List<Map<String,Widget>> and one function to remove items from it, and one function to add to it, and both setState the console is printing that the item removed is actually correct, but on the interface, it's only the last item is removed, and somehow the widget that is to be removed is still there on the interface.
Here are the two functions:
addPage() {
String i = pageHolder.ins.pages[pageHolder.ins.pages.length - 2].keys.first;
pageHolder.ins.pages.insert(pageHolder.ins.pages.length - 1, {
"${int.parse(i) + 1}":
PageWidget(callback: removePage, index: int.parse(i) + 1)
});
setState(() {});
}
removePage(String index) {
print("remove page index recerived: $index");
var i = (pageHolder.ins.pages)
.indexWhere((element) => element.keys.first == index);
print("should be removing at: $i");
pageHolder.ins.pages.removeAt(i);
setState(() {});
}
and here is what i get in the console:
[{0: PageWidget}, {1: PageWidget}, {2: PageWidget}, {7: PageWidget}, {8: PageWidget}, {9: PageWidget}, {: Adder}]
remove page index recerived: 7
should be removing at: 3
[{0: PageWidget}, {1: PageWidget}, {2: PageWidget}, {8: PageWidget}, {9: PageWidget}, {: Adder}]
here is the widget code:
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:teacher_page/classes/pageHolder.dart';
import 'classes/audiostreamer.dart';
class PageWidget extends StatefulWidget {
final index;
final callback;
const PageWidget({super.key, this.index, this.callback});
#override
State<PageWidget> createState() => _PageWidgetState();
}
class _PageWidgetState extends State<PageWidget>
with AutomaticKeepAliveClientMixin {
#override
void initState() {
print("init state is called again and index is:${widget.index}");
super.initState();
}
bool imageAvailable = false;
late Uint8List imageBytes;
late Uint8List AudioBytes;
final player = AudioPlayer();
bool audioAvailable = false;
#override
Widget build(BuildContext context) {
return pageContainer();
}
placeholder() {
return Container(
color: Colors.purple.withOpacity(0.5),
child: const Center(
child: Text(
"Pick your image",
style: TextStyle(color: Colors.white),
)),
);
}
pageContainer() {
return Container(
margin: const EdgeInsets.only(left: 30, top: 100, right: 30, bottom: 50),
height: double.infinity,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10)),
boxShadow: [
BoxShadow(
color: Colors.purple.withOpacity(0.5),
spreadRadius: 3,
blurRadius: 7,
offset: const Offset(0, 3), // changes position of shadow
),
],
),
child: Column(
children: [
Expanded(
child: InkWell(
child: imageAvailable ? Image.memory(imageBytes) : placeholder(),
onTap: () async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'png'],
);
if (result != null) {
setState(() {
imageBytes = result.files[0].bytes!;
imageAvailable = true;
});
// File file = File(result.files.single.path);
} else {
// User canceled the picker
}
},
),
),
Row(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: audioAvailable
? Colors.purple
: Colors.grey, // This is what you need!
),
onPressed: () async {
if (audioAvailable) {
await player.setAudioSource(JABytesSource(AudioBytes));
player.play();
}
},
icon: const Icon(Icons.play_arrow),
label: const Text("Play")),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton.icon(
onPressed: () async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['mp3', 'wav'],
);
if (result != null) {
setState(() {
AudioBytes = result.files[0].bytes!;
audioAvailable = true;
});
// File file = File(result.files.single.path);
} else {
// User canceled the picker
}
},
icon: const Icon(Icons.file_upload),
label: const Text("Pick an audio file")),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: (widget.index > 2)
? ElevatedButton.icon(
onPressed: () async {
// print("remove is called: ${widget.index}");
widget.callback(widget.index.toString());
},
icon: const Icon(Icons.delete),
label: Text("${widget.index}"))
: null,
),
],
),
TextField(
onChanged: (text) {
print("THe text is:$text");
print(pageHolder.ins.pages);
// pageHolder.ins.pages;
},
style: const TextStyle(color: Colors.purple, fontSize: 24),
decoration: const InputDecoration(
fillColor: Colors.white,
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8))),
labelText: 'Word or the sentence for the picture',
labelStyle: TextStyle(
color: Colors.purple, fontSize: 24, fontFamily: "sans-serif"),
floatingLabelStyle: TextStyle(
color: Color.fromARGB(255, 191, 116, 204), fontSize: 24),
),
),
],
),
);
}
#override
// TODO: implement wantKeepAlive
bool get wantKeepAlive => true;
}
I'm trying to write a shopping app. But unfortunately I stuck with loading and displaying the products from firebase with the help of the package provider.
In the app you can get from the searchPage to the ResultPage. In the ResultPage a GridView.builder should display the products whose category matches your entered searchtext from the SearchPage.
From the ResultPage you can also get to a FilterScreen where you can set filters. After you have left this screen you should only see the products on the result screen which matches your filters.
But this isn't working at all. Instead of seeing the filtered products there are no products displayed. But I get no error message. So I really stuck at this problem.
I don't even know where it's coming from.
I would be very thankful if anyone could help me!
This is my result page code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shs/providers/filters_provider.dart';
import 'package:shs/providers/products_provider.dart';
import 'package:shs/screens/filters_screen.dart';
import 'package:shs/widgets/bottom_navigation_bar.dart';
import 'package:shs/widgets/filter_overlay.dart';
import 'package:shs/widgets/my_scaffold.dart';
import 'package:shs/widgets/product_grid.dart';
import '../widgets/size_grid.dart';
import '../widgets/size_grid_buchstaben.dart';
class ResultPage extends StatefulWidget {
String searchtext;
String? gender;
ResultPage(
this.searchtext,
this.gender,
);
#override
State<ResultPage> createState() => _ResultPageState();
}
class _ResultPageState extends State<ResultPage> {
final searchController = TextEditingController();
#override
void initState() {
searchController.addListener(() => setState(() {}));
super.initState();
}
#override
Widget build(BuildContext context) {
return MyScaffold(
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 30,
),
Container(
height: 47,
margin: EdgeInsets.only(top: 30, left: 30, right: 30),
child: TextField(
onSubmitted: ((value) {
setState(() {
widget.searchtext = value;
});
}),
controller: searchController,
textInputAction: TextInputAction.search,
style: Theme.of(context).textTheme.bodyMedium,
decoration: InputDecoration(
fillColor: Colors.white,
suffixIcon: searchController.text.isEmpty
? Container(
width: 0,
)
: IconButton(
onPressed: () {
searchController.clear();
},
icon: Icon(
Icons.close_rounded,
color: Colors.black,
)),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(15)),
prefixIcon: Container(
padding: const EdgeInsets.only(top: 5, left: 8),
child: Image.asset(
'lib/asset/icons/Search.png',
),
),
hintText: 'Search',
hintStyle: Theme.of(context).textTheme.bodyMedium,
),
),
),
SizedBox(
height: 30,
),
Padding(
padding: const EdgeInsets.only(right: 230),
child: Container(
width: 109,
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Theme.of(context).colorScheme.primary,
),
child: GestureDetector(
onTap: () {
Navigator.of(context).pushNamed(FiltersScreen.routeName);
},
child: Row(
children: [
SizedBox(
width: 10,
),
Icon(Icons.filter_list_alt),
SizedBox(
width: 10,
),
Text(
'Filter',
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(fontSize: 15),
)
],
),
)),
),
SizedBox(
height: 30,
),
Consumer<FilterProvider>(
builder: (context, filters, _) => ProductGrid(
filterColor: filters.filterMap['color']!,
filterZustand: filters.filterMap['state']!,
filtersize: filters.filterMap['size']!,
filterProdCat: widget.searchtext,
filterprice: filters.filteredPrice,
)), //Marke noch überall hnzufügen, wenn Filter eingefügt + searchtext zur filters.filterList hinzufügen und wie die anderen darauf referenzieeren, Suchfeld für alle Attribute verwendbar machen
SizedBox(
height: 30,
),
MyBottomNavigationBar(),
],
)),
);
}
}
This is my FilterProviderCode
import 'package:flutter/material.dart';
class FilterProvider with ChangeNotifier {
Map<String, List<String>> _filterMap = {'size': [], 'state': [], 'color': []};
double? filteredPrice;
var _expandedSize = false;
var _expandedPrice = false;
var _expandedState = false;
var _expandedColor = false;
var _expandedBrand = false;
bool _selected = false;
bool get selected {
return _selected;
}
bool _selectedSize = false;
bool _selectedState1 = false;
bool _selectedState2 = false;
bool _selectedState3 = false;
bool _selectedState4 = false;
bool _selectedState5 = false;
bool _selectedColor1 = false;
bool _selectedColor2 = false;
bool _selectedColor3 = false;
bool _selectedColor4 = false;
bool _selectedColor5 = false;
bool _selectedColor6 = false;
bool _selectedColor7 = false;
bool _selectedColor8 = false;
bool get selectedSize {
return _selectedSize;
}
Map<String, List<String>> get filterMap {
return _filterMap;
}
void setSelectedSize(bool variable) {
_selectedSize = variable;
}
void setSelectedState1(bool variable) {
_selectedState1 = variable;
}
void setSelectedState2(bool variable) {
_selectedState2 = variable;
}
void setSelectedState3(bool variable) {
_selectedState3 = variable;
}
void setSelectedState4(bool variable) {
_selectedState4 = variable;
}
void setSelectedState5(bool variable) {
_selectedState5 = variable;
}
void setSelectedColor1(bool variable) {
_selectedColor1 = variable;
}
void setSelectedColor2(bool variable) {
_selectedColor2 = variable;
}
void setSelectedColor3(bool variable) {
_selectedColor3 = variable;
}
void setSelectedColor4(bool variable) {
_selectedColor4 = variable;
}
void setSelectedColor5(bool variable) {
_selectedColor5 = variable;
}
void setSelectedColor6(bool variable) {
_selectedColor6 = variable;
}
void setSelectedColor7(bool variable) {
_selectedColor7 = variable;
}
void setSelectedColor8(bool variable) {
_selectedColor8 = variable;
}
bool get selectedState1 {
return _selectedState1;
}
bool get selectedState2 {
return _selectedState2;
}
bool get selectedState3 {
return _selectedState3;
}
bool get selectedState4 {
return _selectedState4;
}
bool get selectedState5 {
return _selectedState5;
}
bool get selectedColor1 {
return _selectedColor1;
}
bool get selectedColor2 {
return _selectedColor2;
}
bool get selectedColor3 {
return _selectedColor3;
}
bool get selectedColor4 {
return _selectedColor4;
}
bool get selectedColor5 {
return _selectedColor5;
}
bool get selectedColor6 {
return _selectedColor6;
}
bool get selectedColor7 {
return _selectedColor7;
}
bool get selectedColor8 {
return _selectedColor8;
}
bool get expandedSize {
return _expandedSize;
}
bool get expandedPrice {
return _expandedPrice;
}
bool get expandedState {
return _expandedState;
}
bool get expandedColor {
return _expandedColor;
}
bool get expandedBrand {
return _expandedBrand;
}
void expandSize() {
_expandedSize = !_expandedSize;
notifyListeners();
}
void expandPrice() {
_expandedPrice = !_expandedPrice;
notifyListeners();
}
void expandState() {
_expandedState = !_expandedState;
notifyListeners();
}
void expandColor() {
_expandedColor = !_expandedColor;
notifyListeners();
}
void expandBrand() {
_expandedBrand = !_expandedBrand;
notifyListeners();
}
void applyFilter(String key, String entry) {
_selected = !_selected;
if (_selected) {
_filterMap[key]!.add(entry);
}
if (_selected == false) {
_filterMap[key]!.removeWhere((element) => element == entry);
}
print(_filterMap);
notifyListeners();
}
void applyFilterUpdate(double entry) {
filteredPrice = entry;
notifyListeners();
print(filteredPrice);
}
}
This is my ProductProvider Code
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:shs/models/product.dart';
class ProductProvider with ChangeNotifier {
final db = FirebaseFirestore.instance;
List<Product> _items = [];
List<Product> get items {
return [..._items];
}
/*Stream<QuerySnapshot> get stream {
return db
.collection('products')
.withConverter(
fromFirestore: Product.fromFirestore,
toFirestore: (Product product, _) => product.toFirestore(),
)
.snapshots();
}*/
Future<void> fetchProducts(
{required bool showAll,
List<dynamic>?
filtersize, //List ist halt manchmal leer wie bei allen anderen
double? filterprice,
List<dynamic>? filterZustand,
//required List<String>? filterMarke,
List<dynamic>? filterColor,
String? filterProdCat}) async {
List<Product> filteredProducts = [];
List<Product> allProducts = [];
List<String> allIDs = [];
final ref = db.collection('products').withConverter(
fromFirestore: Product.fromFirestore,
toFirestore: (Product product, _) => product.toFirestore(),
);
ref.snapshots().listen((event) {
List<String> products = [];
for (var doc in event.docs) {
products.add(doc.id);
allIDs = products;
}
});
allIDs.forEach((id) async {
final docSnap = await ref.doc(id).get();
final product = docSnap.data();
if (product != null) {
allProducts.add(product);
} else {
print('No such document.');
}
});
filteredProducts = allProducts.where((product) {
return filtersize!.contains(product
.size) || //Liste ist halt manchmal leer, also nur wahr wenn auch wirklich Filter gesetzt sind
product.price == filterprice ||
filterZustand!.contains(product.zustand) ||
//filterMarke.contains(product.marke) ||
filterColor!.contains(product.color) ||
product.prodCat == filterProdCat;
}).toList(); // nur wenn filtern erwünscht alle Filter Lists angeben, auch wenn sie leer sind sonst null
if (showAll) {
_items = allProducts;
} else {
_items = filteredProducts;
}
//notifyListeners();
}
}
This is my FiltersScreen Code
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shs/providers/filters_provider.dart';
import 'package:shs/widgets/filter_color.dart';
import 'package:shs/widgets/filter_state.dart';
import 'package:shs/widgets/marked_text.dart';
import 'package:shs/widgets/size_grid.dart';
import 'package:shs/widgets/size_grid_buchstaben.dart';
import 'package:shs/widgets/size_grid_hosen.dart';
import 'package:shs/widgets/size_grid_shoes.dart';
class FiltersScreen extends StatefulWidget {
static const routeName = '/filters';
#override
State<FiltersScreen> createState() => _FiltersScreenState();
}
class _FiltersScreenState extends State<FiltersScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
leading: IconButton(
icon: Icon(
Icons.close,
size: 50,
),
onPressed: () {
Navigator.of(context).pop();
},
),
backgroundColor: Theme.of(context).colorScheme.primary,
actions: [
GestureDetector(
onTap: () {}, // Navigate to AccountPage
child: Container(
child: Image.asset('lib/asset/icons/Account.png'),
),
),
SizedBox(
width: 7,
),
GestureDetector(
onTap: () {}, // Navigate to ShoppingBag
child: Container(
child: Image.asset('lib/asset/icons/ShoppingBag.png'),
),
),
GestureDetector(
onTap: () {}, // Navigate to Favorite
child: Container(
child: Image.asset('lib/asset/icons/Favorite.png'),
),
),
SizedBox(
width: 7,
),
],
),
body: Consumer<FilterProvider>(
builder: (context, filters, _) => SingleChildScrollView(
child: Column(children: [
SizedBox(
height: 30,
),
Center(
child: MarkedText(
'Filters',
() {},
Theme.of(context).colorScheme.primary,
fontsize: 80,
),
),
SizedBox(
height: 30,
),
ListTile(
title: Text(
'Size',
style: Theme.of(context)
.textTheme
.displayMedium!
.copyWith(fontSize: 50),
),
trailing: IconButton(
onPressed: () {
filters.expandSize();
},
icon: Icon(
filters.expandedSize
? Icons.expand_less
: Icons.expand_more,
size: 50,
color: Colors.black)),
),
if (filters.expandedSize)
Container(
height: 1800,
child: Column(
children: [
SizedBox(
height: 30,
),
SizedBox(
height: 300,
child: Container(
width: 300, height: 500, child: SizeGrid())),
SizedBox(
height: 30,
),
SizedBox(
height: 230,
child:
Container(width: 300, child: SizeGridBuchstaben())),
SizedBox(
height: 30,
),
SizedBox(
height: 450,
child: Container(width: 300, child: SizeGridHosen())),
SizedBox(
height: 30,
),
Text(
'Size Shoes',
style: Theme.of(context)
.textTheme
.displayMedium!
.copyWith(fontSize: 50),
),
SizedBox(
height: 30,
),
SizedBox(
height: 530,
child: Container(width: 300, child: SizeGridShoes())),
SizedBox(
height: 30,
),
],
),
),
ListTile(
title: Text(
'Price',
style: Theme.of(context)
.textTheme
.displayMedium!
.copyWith(fontSize: 50),
),
trailing: IconButton(
onPressed: () {
filters.expandPrice();
},
icon: Icon(
filters.expandedPrice
? Icons.expand_less
: Icons.expand_more,
size: 50,
color: Colors.black)),
),
if (filters.expandedPrice)
Container(
child: Row(children: [
SizedBox(
width: 20,
),
Text(
'bis',
style: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(fontSize: 32),
),
SizedBox(
width: 30,
),
Container(
width: 150,
height: 40,
child: TextField(
keyboardType: TextInputType.number,
onSubmitted: ((value) {
final doubleValue = double.parse(value);
filters.applyFilterUpdate(doubleValue);
}),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15)),
hintText: '\$',
hintStyle: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(fontSize: 24)),
)),
]),
),
ListTile(
title: Text(
'State',
style: Theme.of(context)
.textTheme
.displayMedium!
.copyWith(fontSize: 50),
),
trailing: IconButton(
onPressed: () {
filters.expandState();
},
icon: Icon(
filters.expandedState
? Icons.expand_less
: Icons.expand_more,
size: 50,
color: Colors.black)),
),
if (filters.expandedState) FiltersState(),
ListTile(
title: Text(
'Color',
style: Theme.of(context)
.textTheme
.displayMedium!
.copyWith(fontSize: 50),
),
trailing: IconButton(
onPressed: () {
filters.expandColor();
},
icon: Icon(
filters.expandedColor
? Icons.expand_less
: Icons.expand_more,
size: 50,
color: Colors.black)),
),
if (filters.expandedColor) FilterColor(),
ListTile(
title: Text(
'Brand',
style: Theme.of(context)
.textTheme
.displayMedium!
.copyWith(fontSize: 50),
),
trailing: IconButton(
onPressed: () {
filters.expandBrand();
},
icon: Icon(
filters.expandedBrand
? Icons.expand_less
: Icons.expand_more,
size: 50,
color: Colors.black)),
), //Marken aufzählen List Tile von Zustand verwenden
SizedBox(
height: 30,
),
ElevatedButton(
onPressed: () {
Navigator.of(context).pop(); //Filter anwenden
},
child: Text('Apply Filters!')),
]),
),
),
);
}
}
This is my Product Grid Code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shs/providers/products_provider.dart';
import 'product_card.dart';
class ProductGrid extends StatelessWidget {
ScrollController scrollController = ScrollController();
List<String> filtersize;
List<String> filterColor;
String? filterProdCat;
List<String> filterZustand;
double? filterprice;
ProductGrid(
{required this.filterColor,
this.filterProdCat,
required this.filterZustand,
this.filterprice,
required this.filtersize});
Future<void> updateProducts(
{required BuildContext context,
required List<String> filtersize,
required List<String> filterColor,
//required List<String> filterMarke,
String? filterProdCat,
required List<String> filterZustand,
double? filterprice}) async {
await Provider.of<ProductProvider>(
context,
listen: false,
).fetchProducts(
showAll: false,
filtersize: filtersize,
filterColor: filterColor,
//filterMarke: filterMarke,
filterProdCat: filterProdCat,
filterZustand: filterZustand,
filterprice: filterprice);
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: updateProducts(
context: context,
filtersize: filtersize,
filterColor: filterColor,
filterZustand: filterZustand),
builder: ((context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return Consumer<ProductProvider>(
builder: (ctx, products, _) => GridView.builder(
controller: scrollController,
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: products.items.length,
itemBuilder: ((context, index) => ProductCard(
state: products.items[index].zustand!,
imageUrl: products.items[index].imageUrl,
price: products.items[index].price,
size: products.items[index].size!,
id: products.items[index].id,
prodCat: products.items[index].prodCat,
marke: products.items[index].marke)),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 10,
mainAxisExtent: 400)));
}));
}
}
And here is my dummy product data from firestore
enter image description here
If you need more code or anything else, no problem I will post it!
I'm new to Flutter so my code is a bit messy, I have to admit...
THANK YOU FOR YOUR HELP!
I am trying to build a questionnaire within an application
The idea is that the user answers questions
So every answer he gives is in one question
Accordingly he will receive the following question
For example if he answered a question with answer a
Will get one question
If he answered the same question with answer b
Will get another question later
how can i solve this
The code is attached
Thanks
import 'package:flutter/material.dart';
import 'package:gsheets/question_model.dart';
class QuizScreen extends StatefulWidget {
#override
State<QuizScreen> createState() => _QuizScreenState();
}
class _QuizScreenState extends State<QuizScreen> {
//define the datas
List<Question> questionList = getQuestions();
int currentQuestionIndex = 0;
int score = 0;
Answer? selectedAnswer;
int? nextQuestionId;
int? questionId;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(255, 5, 50, 80),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 32),
child:
Column(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
const Text(
"Simple Quiz App",
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
),
_questionWidget(),
_answerList(),
_nextButton(),
]),
),
);
}
_questionWidget() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Question ${currentQuestionIndex + 1}/${questionList.length.toString()}",
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 20),
Container(
alignment: Alignment.center,
width: double.infinity,
padding: const EdgeInsets.all(32),
decoration: BoxDecoration(
color: Colors.orangeAccent,
borderRadius: BorderRadius.circular(16),
),
child: Text(
questionList[currentQuestionIndex].questionText,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
)
],
);
}
_answerList() {
return Column(
children: questionList[currentQuestionIndex]
.answerList
.map(
(e) => _answerButton(e),
)
.toList(),
);
}
Widget _answerButton(Answer answer) {
bool isSelected = answer == selectedAnswer;
return Container(
width: double.infinity,
margin: const EdgeInsets.symmetric(vertical: 8),
height: 48,
child: ElevatedButton(
child: Text(answer.answerText),
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
primary: isSelected ? Colors.orangeAccent : Colors.white,
onPrimary: isSelected ? Colors.white : Colors.black,
),
onPressed: () {
// if (selectedAnswer == null) {
// if (answer.isCorrect) {
// score++;
// }
setState(() {
selectedAnswer = answer;
});
}
// },
),
);
}
_nextButton() {
// if(answer == )
bool isLastQuestion = false;
if (currentQuestionIndex == questionList.length - 1) {
isLastQuestion = true;
}
return Container(
width: MediaQuery.of(context).size.width * 0.5,
height: 48,
child: ElevatedButton(
child: Text(isLastQuestion ? "Submit" : "Next"),
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
primary: Colors.blueAccent,
onPrimary: Colors.white,
),
onPressed: () {
// if(nextQuestionId == questionId)
if (isLastQuestion) {
//display score
showDialog(context: context, builder: (_) => _showScoreDialog());
} else {
//next question
setState(() {
selectedAnswer = null;
currentQuestionIndex++;
});
}
},
),
);
}
_showScoreDialog() {
bool isPassed = false;
if (score >= questionList.length * 0.6) {
//pass if 60 %
isPassed = true;
}
String title = isPassed ? "Passed " : "Failed";
return AlertDialog(
title: Text(
title + " | Score is $score",
style: TextStyle(color: isPassed ? Colors.green : Colors.redAccent),
),
content: ElevatedButton(
child: const Text("Restart"),
onPressed: () {
Navigator.pop(context);
setState(() {
currentQuestionIndex = 0;
score = 0;
selectedAnswer = null;
});
},
),
);
}
}
========================
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gsheets/quiz.dart';
class Question {
final String questionText;
final List<Answer> answerList;
final int questionId;
Question(this.questionText, this.answerList, this.questionId);
}
class Answer {
final String answerText;
final int nextQuestionId;
// final bool selectedOption;
Answer(this.answerText, this.nextQuestionId);
}
List<Question> getQuestions() {
List<Question> list = [];
list.add(Question(
"Which school did you learn",
[
Answer("a", 3),
Answer("b", 2),
],
3,
));
list.add(Question(
"what is your age",
[
Answer("18", 3),
Answer("20", 5),
],
2,
));
list.add(Question(
"which car do you drive",
[
Answer("c", 3),
Answer("d", 2),
],
3,
));
return list;
}
I integrated Agora in Flutter Application with the help of agora_rtc_engine 4.0.7, but upon making a video call for the very first time the local camera view is not working. When we disconnect the call and call back again then everything works fine, the local camera view started working.
Again when we kill the application from Phone memory and rerun it then also the same problem occurs for the first time.
VideoCallingScreen.dart file
class VideoCallingScreen extends StatefulWidget {
String doctorId;
String bookingId;
VideoCallingScreen(this.doctorId, this.bookingId);
#override
_VideoCallingScreenState createState() => _VideoCallingScreenState();
}
class _VideoCallingScreenState extends State<VideoCallingScreen> {
int? _remoteUid;
RtcEngine? _engine;
bool isJoined = false,
switchCamera = true,
switchRender = true,
muteAudio = false,
muteVideo = false;
bool remoteUserMicMute = false, remoteUserVideoMute = false;
bool resizeVideo = false;
ServerHandler _serverHandler = ServerHandler();
String? token;
String? channelName;
String? channelId;
late user.Details userDetails;
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
#override
void initState() {
super.initState();
getAgoraToken().then((value) {
if (value) {
initForAgora();
} else {
_showMyDialog();
}
});
// initForAgora();
}
Future<void> _showMyDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: const Text('No Channel Found'),
content: SingleChildScrollView(
child: ListBody(
children: const <Widget>[
Text('No video channel has been created by the Doctor'),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('Ok'),
onPressed: () async {
// int count = 0;
Navigator.pop(context);
Navigator.pop(_scaffoldKey.currentContext!);
},
),
],
);
},
);
}
Future<bool> getAgoraToken() async {
await Screen.keepOn(true);
var tokenBody = await _serverHandler.joinAgoraChannel(
widget.doctorId, widget.bookingId);
print('token Body from videoPage' + tokenBody.toString());
if (tokenBody['success'] == 1) {
setState(() {
token = tokenBody['channel']['access_token_patient'];
channelName = tokenBody['channel']['channel_name'];
print('**********Token Set********' + token!);
channelId = tokenBody['channel']['id'].toString();
});
return true;
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
"Unable to get Video Call Token, Please check your internet Connection and try again."),
));
return false;
}
}
Future<void> initForAgora() async {
// retrieve permissions
await [Permission.microphone, Permission.camera].request();
userDetails = await _serverHandler.getUserProfile();
//create the engine
_engine = await RtcEngine.create(appId);
await _engine?.enableVideo();
_engine?.setEventHandler(
RtcEngineEventHandler(
joinChannelSuccess: (String channel, int uid, int elapsed) async {
print("local user $uid joined");
// await _engine!.enableVideo();
},
userJoined: (int uid, int elapsed) {
print("remote user $uid joined");
setState(() {
_remoteUid = uid;
});
},
tokenPrivilegeWillExpire: (token) async {
await getAgoraToken();
await _engine?.renewToken(token);
},
userOffline: (int uid, UserOfflineReason reason) {
print("remote user $uid left channel");
// _engine!.enableVideo();
setState(() {
_remoteUid = null;
});
_userLeftTheCall();
},
userMuteVideo: (int uid, bool isMute) {
print('Audio Mutted');
setState(() {
remoteUserVideoMute = isMute;
});
},
userMuteAudio: (int uid, bool isMute) {
print('Audio Mutted');
setState(() {
remoteUserMicMute = isMute;
});
},
),
);
await getAgoraToken();
await _engine?.joinChannel(token, channelName!, null, userDetails.id!);
}
// Create UI with local view and remote view
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
key: _scaffoldKey,
body: SafeArea(
child: Stack(
children: [
Center(
child:
resizeVideo ? _renderLocalPreview() : _renderRemoteVideo(),
),
if (remoteUserVideoMute)
BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 10,
sigmaY: 10,
),
child: Padding(
padding: const EdgeInsets.only(bottom: 32),
child: Center(
child: Text(
'Doctor video Paused',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
),
),
),
if (remoteUserMicMute)
Padding(
padding: const EdgeInsets.only(top: 32),
child: Center(
child: Text(
'Doctor Mic Muted',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
),
),
Positioned(
top: 8,
left: 8,
child: InkWell(
//Uncomment it to unable resize
// onTap: () {
// setState(() {
// resizeVideo = !resizeVideo;
// });
// },
child: Container(
width: 100,
height: 120,
child: Stack(
children: [
ImageFiltered(
imageFilter: muteVideo
? ImageFilter.blur(sigmaX: 3.0, sigmaY: 3.0)
: ImageFilter.blur(sigmaX: 0, sigmaY: 0),
child: resizeVideo
? _renderRemoteVideo()
: _renderLocalPreview(), // Widget that is blurred
),
if (muteVideo)
Positioned(
top: 4,
left: 4,
child: Icon(
Icons.videocam_off_outlined,
color: Colors.white,
size: 32,
),
),
if (muteAudio)
Positioned(
bottom: 4,
right: 4,
child: Icon(
Icons.mic_off_outlined,
color: Colors.white,
size: 32,
),
),
],
),
),
),
),
Positioned(
bottom: 32,
right: 8,
left: 8,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
InkWell(
onTap: () async {
await Screen.keepOn(false);
await _engine?.leaveChannel();
await _serverHandler.leaveChannel(channelId!);
Navigator.pop(_scaffoldKey.currentContext!);
},
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: Colors.red),
child: Icon(
Icons.call_end,
color: Colors.white,
),
),
),
InkWell(
onTap: this._switchCamera,
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: Colors.white),
child: Icon(
Icons.flip_camera_android_rounded,
color: Colors.black87,
),
),
),
InkWell(
onTap: this._onToggleMuteVideo,
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: Colors.white),
child: Icon(
muteVideo
? Icons.videocam_off_outlined
: Icons.videocam_outlined,
color: Colors.black87,
),
),
),
InkWell(
onTap: this._onToggleMute,
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: Colors.white),
child: Icon(
muteAudio
? Icons.mic_off_outlined
: Icons.mic_none_outlined,
color: Colors.black87,
),
),
),
],
),
)
],
),
),
),
);
}
// current user video
Widget _renderLocalPreview() {
return RtcLocalView.SurfaceView();
}
// remote user video
Widget _renderRemoteVideo() {
// return RtcRemoteView.SurfaceView(uid: 70);
if (_remoteUid != null) {
return RtcRemoteView.SurfaceView(uid: _remoteUid!);
} else {
return Text(
'Please wait, doctor is joining shortly',
style: TextStyle(
color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
);
}
}
_switchCamera() {
_engine?.switchCamera().then((value) {
setState(() {
switchCamera = !switchCamera;
});
}).catchError((err) {
log('switchCamera $err');
});
}
void _onToggleMute() {
setState(() {
muteAudio = !muteAudio;
});
_engine!.muteLocalAudioStream(muteAudio);
}
void _onToggleMuteVideo() {
setState(() {
muteVideo = !muteVideo;
});
_engine!.muteLocalVideoStream(muteVideo);
}
Future<bool> _onWillPop() async {
return (await showDialog(
context: _scaffoldKey.currentContext!,
builder: (context) => new AlertDialog(
title: new Text('Are you sure?'),
content: new Text('Do you want to exit exit Video Call?'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(_scaffoldKey.currentContext!),
child: new Text('No'),
),
TextButton(
onPressed: () async {
await Screen.keepOn(false);
await _serverHandler.leaveChannel(channelId!);
await _engine?.leaveChannel();
Navigator.pop(_scaffoldKey.currentContext!);
Navigator.pop(_scaffoldKey.currentContext!);
},
child: new Text('Yes'),
),
],
),
)) ??
false;
}
_userLeftTheCall() async {
return (await showDialog(
context: _scaffoldKey.currentContext!,
builder: (context) => new AlertDialog(
title: new Text('Doctor Left'),
content: new Text('Doctor left this call please join Again'),
actions: <Widget>[
TextButton(
onPressed: () async {
// await _serverHandler.leaveChannel(channelId!);
await Screen.keepOn(false);
await _engine?.leaveChannel();
Navigator.pop(_scaffoldKey.currentContext!);
Navigator.pop(_scaffoldKey.currentContext!);
// Navigator.of(context).pop(true);
},
child: new Text('Okay'),
),
],
),
)) ?? false;
}
}
Please ignore things which are not relevent. Also the log is too long to share, the log keeps on running during the entire video call.
Mobile Screenshot
Thank You
I have a Flutter code. instead of showing nothing when the submit button is clicked, I want to show the circular loading indicator when the button is clicked so to keep the user busy but I'm having a challenge to convert a tutorial I have that does that to a work with my code.
Here is the tutorial:
...
children: <Widget>[
new Padding(
padding: const EdgeInsets.all(16.0),
child: new MaterialButton(
child: setUpButtonChild(),
onPressed: () {
setState(() {
if (_state == 0) {
animateButton();
}
});
},
elevation: 4.0,
minWidth: double.infinity,
height: 48.0,
color: Colors.lightGreen,
),
)
],
Widget setUpButtonChild() {
if (_state == 0) {
return new Text(
"Click Here",
style: const TextStyle(
color: Colors.white,
fontSize: 16.0,
),
);
} else if (_state == 1) {
return CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
);
} else {
return Icon(Icons.check, color: Colors.white);
}
}
void animateButton() {
setState(() {
_state = 1;
});
Timer(Duration(milliseconds: 1000), () {
setState(() {
_state = 2;
});
});
Timer(Duration(milliseconds: 3300), () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => AnchorsPage(),
),
);
});
}
Here's my code. All I want to do is to display the CircularProgressIndicator when the system is performing the HTTP request.
And here is my code where I want to use the CircularProgressIndicator:
Center(
child:
RaisedButton(
padding: EdgeInsets.fromLTRB(80, 10, 80, 10),
color: Colors.green,
child: setUpButtonChild(),
onPressed: () {
setState(()async {
_state = 1;
var toSubmit = {
"oid": EopOid,
"modifiedBy": user['UserName'].toString(),
"modifiedOn": DateTime.now().toString(),
"submitted": true,
"submittedOn": DateTime.now().toString(),
"submittedBy": user['UserName'].toString()
};
for (EopLine i in selectedEops) {
var item = {
"oid": i.oid.toString(),
"quantityCollected": i.quantityCollected,
"modifiedBy": user['UserName'].toString(),
"modifiedOn": DateTime.now().toString(),
};
await http
.put(
"http://api.ergagro.com:112/UpdateEopLine",
headers: {
'Content-Type': 'application/json'
},
body: jsonEncode(item))
.then((value) async {
if (selectedEops.indexOf(i) ==
selectedEops.length - 1) {
await http
.put(
"http://api.ergagro.com:112/SubmitEop",
headers: {
'Content-Type':
'application/json'
},
body: jsonEncode(toSubmit))
.then((value) {
print('${value.statusCode} submitted');
Navigator.pop(context);
});
}
});
}
_state = 2;
});
//Navigator.of(context).push(MaterialPageRoute(
//builder: (context) =>
//StartScanPage(widget.dc_result)));
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
),
If you're using a button with the icon() constructor (icon + text), you can swap the icon with the CircularProgressIndicator when the button state changes. It works because both the icon and the indicator are widgets:
return ElevatedButton.icon(
onPressed: _isLoading ? null : _onSubmit,
style: ElevatedButton.styleFrom(padding: const EdgeInsets.all(16.0)),
icon: _isLoading
? Container(
width: 24,
height: 24,
padding: const EdgeInsets.all(2.0),
child: const CircularProgressIndicator(
color: Colors.white,
strokeWidth: 3,
),
)
: const Icon(Icons.feedback),
label: const Text('SUBMIT'),
);
Live Demo
You can copy paste run full code below
You can directly use package https://pub.dev/packages/progress_indicator_button
or reference it's source code
You can pass AnimationController to http job and use controller.forward and reset
code snippet
void httpJob(AnimationController controller) async {
controller.forward();
print("delay start");
await Future.delayed(Duration(seconds: 3), () {});
print("delay stop");
controller.reset();
}
...
ProgressButton(
borderRadius: BorderRadius.all(Radius.circular(8)),
strokeWidth: 2,
child: Text(
"Sample",
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
),
onPressed: (AnimationController controller) async {
await httpJob(controller);
}
working demo
full code
import 'package:flutter/material.dart';
import 'package:progress_indicator_button/progress_button.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
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;
void _incrementCounter() {
setState(() {
_counter++;
});
}
void httpJob(AnimationController controller) async {
controller.forward();
print("delay start");
await Future.delayed(Duration(seconds: 3), () {});
print("delay stop");
controller.reset();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: 200,
height: 60,
child: ProgressButton(
borderRadius: BorderRadius.all(Radius.circular(8)),
strokeWidth: 2,
child: Text(
"Sample",
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
),
onPressed: (AnimationController controller) async {
await httpJob(controller);
},
),
),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
You can also use ternary operator to output based on some _isLoading state variable and make use of CircularProgressIndicator(), of course this is a simple solution without using any third party libraries.
#override
Widget build(BuildContext context) {
return TextButton(
onPressed: () {},
child: Container(
padding: const EdgeInsets.all(10),
child: _isLoading
? SizedBox(
height: 25,
width: 25,
child: CircularProgressIndicator(),
)
: Text('ORDER NOW'),
),
);
}