I wanted to change text 'tap' and 'tapped' with tap like this code below, but it doesn't change the text.
I can seeprint(isTapped)
works, but why the text doesn't change?
Did I put bool isTapped = false;
wrong place? or Am I totally misunderstanding?
I just want change the text 'tap' and 'tapped'.
I'm new to flutter and programming.
class TestBool extends StatefulWidget {
const TestBool({Key? key}) : super(key: key);
@override
_TestBoolState createState() => _TestBoolState();
}
class _TestBoolState extends State<TestBool> {
bool isTapped = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: double.infinity,
width: double.infinity,
color: Colors.red,
child: GestureDetector(
onTap: () {
showModalBottomSheet(
backgroundColor: Colors.transparent,
isScrollControlled: true,
context: context,
builder: (context) => DraggableScrollableSheet(
initialChildSize: 0.5,
builder: (_, controller) => Container(
color: Colors.white,
child: GestureDetector(
onTap: () {
setState(() {
isTapped = !isTapped;
});
print(isTapped);
},
child: Center(child: Text(isTapped ? 'tap' : 'tapped')),
),
)
),
);
},
child: Image.asset('images/commenticon.png'),
),
),
);
}
} ```
CodePudding user response:
Thats because you are using a stateless ModalBottomSheet, so it doesn't have a state to update. The solution for this is to use StatefulBuilder
, example:
Scaffold(
body: Container(
height: double.infinity,
width: double.infinity,
color: Colors.red,
child: GestureDetector(
onTap: () {
showModalBottomSheet(
backgroundColor: Colors.transparent,
isScrollControlled: true,
context: context,
builder: (context) =>
StatefulBuilder(
builder: (BuildContext context, StateSetter stateSetter {return
DraggableScrollableSheet(
initialChildSize: 0.5,
builder: (_, controller) => Container(
color: Colors.white,
child: GestureDetector(
onTap: () {
setState(() {
isTapped = !isTapped;
});
print(isTapped);
},
child: Center(child: Text(isTapped ? 'tap' : 'tapped')),
),
)
);
}));
},
child: Image.asset('images/commenticon.png'),
),
),
);